Blog

  • C – Decision Making Statements

    In C programming Language, Decision-Making statements are used when a user wants a certain block to be executed under certain conditions.

    It also allows the user to determine the order in which a certain block has to be executed, or repeat that block until the certain condition is fulfilled.

    C programming language provides the following types of decision-making statements:


    if statement in C

    An if statement consists of a Boolean expression followed by one or more statements. If the boolean expression is true, the block of code inside the if statement will be executed else not.

    Syntax of if statement in C:

     if (boolean expression)
      {
       /* if expression is true */
       statements... ; /* Execute statements */
      }

    if…else statement in C

    If the Boolean expression is true then the code inside the if statement block is executed or if it is false then the code inside else statement will be executed. Hence if..else statement.

    Syntax of if...else statement in C:

     if (condition) 
     {
      //code executed if condition true 
     }
     else
     {
      //code executed if condition false 
     }

    nested if statement in C

    This statement allows the user to use if block inside the other if block. And the inner if statement is executed only if the outer if statement’s condition is true.

    Syntax of nested if statement in C:

    if(condition1)
     {    
        //block of code to be executed    
        if(condition2)
        {  
          //block of code to be executed    
        }    
     } 

    switch statement in C

    A switch statement allows a variable to be tested for equality against multiple values and each of those values is called a case. It can be used instead of nested if...else.

    Switch expression and case value must be of the same type. There must be at least one case or multiple cases with unique case values. In the end, it can have a default case which is optional that is executed if no cases are matched.

    Syntax of switch statement in C:

    switch (expression)
    {
        case value1:    
               //code to be executed;    
               break;  //optional  
        case value2:    
                //code to be executed;    
                break;  //optional  
        .
        .
        .
        .    
        case valueN:    
                //code to be executed;    
                break;  //optional 
            
        default:     
               code to be executed if all cases are not matched;    
      }

    nested switch statement in C

    The use of switch statement inside another switch statement is called nested switch statement.

    Syntax of nested switch statement in C:

    switch(ch1) {
    
       case 'A': 
          printf("This A is part of outer switch" );
          
          //use of another switch statement
          switch(ch2) {
             case 'A':
                printf("This A is part of inner switch" );
                break;
             case 'B': /* case code */
          }
    	  
          break;
       case 'B': /* case code */
    }

    The ? : Operator

    ? : This operator is called a conditional operator or ternary operator. The execution of this operator depends on the result of binary condition.

    Ternary Operator can also be used instead of if...else statement as it does follow the same algorithm and the only difference is ternary operator takes less space and it’s the short version of if...else statement.

    ? : Operator is also called Ternary Operator because it takes three operands to operate, as shown in the syntax below.

    Syntax of Ternary Operator:

    variable = Condition ? Expression1 : Expression1

    Here, the condition that is the binary condition is to be evaluated. And if the binary condition is true then Expression1 is executed and if it is false then Expression2 is executed. And both of them return the results.

    Example of Ternary Operator in C:

    #include <stdio.h>
    
    int main()
    {
     	// declaring variables
      int num1 = 5, num2 = 10, minNum;
    
      /*Using Ternary Operator
      to find smallest among
      num1 and num2 */
      minNum = (num1 > num2) ? num1 : num2;
    
     	// Display Smallest Number
      printf("The smallest number is: %d", minNum);
    
      return 0;
    }

    The Output of Ternary Operator:

    The smallest number is: 10

  • C – Tokens

    What is Token in C?

    The basic and smallest unit of a C program is called C tokens. This tokens are meaningful to the compiler. Compiler breaks the programs into smallest unit that is the tokens and proceed various compilation stages.

    There are total six tokens in C Programming language.

    token in C
    Tokens in C

    Keywords and Identifiers:

    Keywords are defined as the predefined, reserved word that has a fixed meaning and those meanings cannot be changed. There are a total of 32 keywords in ‘C’.

    The table below represent 32 Keyword in the C Programming language:

    autodoubleintstruct
    breakelselongswitch
    caseenumregistertypedef
    charexternreturnunion
    constfloatshortunsigned
    continueforsignedvoid
    defaultgotosizeofvolatile
    doifstaticwhile

    Identifiers are nothing but the name assigned to the entities in the Program such as assigned to variables, functions in a program, Union, etc. Identifiers are user-defined in C Programming. These identifiers are case-sensitive, the first character must start with an alphabet or underscore, and no white spaces are allowed.

    Operators:

    Operators are the mathematical symbols that are used to perform a mathematical operation on operands. These symbols tell the compiler to perform respective operations. An expression is formed by joining constants and variables in C programming.

    Example: + symbol used to perform addition between two or more than two operands. Other symbols are: -, *, /, etc.

    Strings:

    C programming defined string as a sequence or array of characters that are terminated by character ‘\0‘.
    Example: str[]= “Strings Example”. These are enclosed within ” “.

    Constants:

    From the name constant, we can say that these are fix values that are used in a program and its values remain the same during the entire execution of the program. Also, we cannot change the value in the middle of the program.
    These constants may be any of the data-types present in C such as integer, float, boolean, etc.

    Special Characters in C:

    There are few special characters or special symbol in C programming language that has some special meaning and purposes.

    They are: [] () {}, ; * = #.

    Example: [] (opening and closing brackets) is used for array elements reference.

  • C – Input output(I/O): printf, scanf, getchar & putchar

    Input output(I/O)

    Input means providing or inserting some data that is to be used in a program.
    Output means to display the data on the screen or write it in a file.

    There are many C built-in function that are used to take in data and display the data from a program as a result.

    printf() and scanf() functions

    printf() and scanf() are a C built in function whose definition are present in the standard input-output header file, named stdio.h.

    printf() takes the values given to it and display it on a screen.
    scanf() is used to take in user input and store it in some variable to use it in a program.

    Example to show the use of printf() and scanf() in a C program:

    #include <stdio.h>
    
    void main()
    {
      //defining a variable
      int i;
    
      /*Displaying to the user to enter value */
      printf("Enter the Value: ");
    
      /*reading the value*/
      scanf("%d", &i);
    
      /*Displaying the entered number as a output.*/
      printf("\nEntered number is: %d", i);
    }

    The output of printf() and scanf() in C.

    Enter the Value: 489
    
    Entered number is: 489

    The following table shows the use of %d, %f, etc in a above program.

    Format StringMeaning
    %dScan or print an integer as signed decimal number
    %fScan or print a floating point number
    %cscan or print a character
    %sscan or print a character string

    getchar() & putchar() functions

    getchar() is used to read a character from the terminals(keyboard) and reads only a single character at a time.
    putchar() is used to write a character on the screen. This is mainly used in File handling in C.

    Both the function only displays one character at a time so if the user needs to display it more than one time then it needs to be used with loops.

    Example to show the use of getchar() & putchar() in a C program:

    #include <stdio.h>
    
    void main()
    {
      int ch;
      printf("Enter a character you want: ");
    
     //taking character as an input
      ch = getchar();
    
      printf("The Entered character is: ");
     //Display the character
      putchar(ch);
    }

    The output of getchar() & putchar() in C.

    Enter a character you want: A
    The Entered character is: A
  • C – Keywords and Identifiers

    In this article you will learn about the Keywords, Identifiers and Tokens present in C. Let us first start with Character sets, knowing what are character sets then you will understand the rest in this article.
    Let us begin.

    Character sets:

    In C Programming Character Sets refers to all the alphabets, letters and some special characters that are used in a program.

    Keywords

    Keywords are defined as the reserved word that has a fixed meaning and those meanings cannot be changed. These are predefined by the program. There are a total of 32 keywords in ‘C’.

    • Keywords cannot be used as variables.
    • These are predefined by the compiler with special meaning.
    • There are 32 Keywords in c Programming.

    For example: int temp;

    The table below represent list of 32 Keyword in C Programming language:

    autodoubleintstruct
    breakelselongswitch
    caseenumregistertypedef
    charexternreturnunion
    continueforsignedvoid
    doifstaticwhile
    defaultgotosizeofvolatile
    constfloatshortunsigned

    Identifiers

    Identifiers are nothing but the name assigned to the entities such as variables, functions in a program, Union, etc. Identifiers are user-defined in C Programming.

    The name assigned to the entities is unique so that it can be identified during the execution of the program. Identifiers cannot be used as Keywords.

    Example: int salary;, salary being identifier.

    Rules for naming identifiers:

    • Identifiers are case-sensitive.
    • The first letter of identifiers must be a letter or underscore.
    • White spaces are not allowed.
    • There is no rule to decide the length of the name of identifiers.

    Some valid and invalid identifiers:

    //Valid
    Number  
    result1  
    _multiply  
    S2C
    
    //Invalid
    Number-2   //special character '-' is present.  
    3Sum    //started with digit   
    int    // int is a keyword     

    What is Token in C?

    The basic and smallest unit of a C program is called C tokens. These tokens are meaningful to the compiler. The compiler breaks the programs into the smallest unit that is the tokens and proceed with various compilation stages.

    There are total six tokens in C Programming language.

    token in C
    Tokens in C

    Keywords:

    Keywords are reserved words whose meaning is predefined by the programming language specification. They convey some special meaning in programming and we must not use them for other purposes. They are basically a sequence of characters that have fixed to mean for example break, for, while, do-while, do, if, int, long, char.

    Identifiers

    Identifiers are names for entities in a C program, such as variables, arrays, functions, structures, unions, and labels. An identifier can be composed only of uppercase, lowercase letters, underscore and digits, but should only start with an alphabet or an underscore.

    Operators:

    Operators are the mathematical symbols that are used to perform a mathematical operation on operands. These symbols tell the compiler to perform respective operations. An expression is formed by joining constants and variables in C programming.

    Example: + symbol used to perform addition between two or more than two operands. Other symbols are: -, *, /, etc.

    Strings:

    C programming defined string as a sequence or array of characters that are terminated by character ‘\0‘.
    Example: str[]= “Strings Example”. These are enclosed within ” “.

    Constants:

    From the name constant, we can say that these are fix values that are used in a program and its values remain the same during the entire execution of the program. Also, we cannot change the value in the middle of the program.

    These constants may be any of the data-types present in C such as integer, float, boolean, etc.

    Special Characters in C:

    There are few special characters or special symbol in C programming language that has some special meaning and purposes. They are: [] () {}, ; * = #.

    Example: [] (opening and closing brackets) is used for array elements reference.


  • C -Introduction

    C is one of the most commonly used programming languages. It is a general-purpose, high-level language (generally denoted as structured language). C is used for creating a compiler of different languages, implementation of different Operating System Operations.

    C programming language was first developed by Dennis M. Ritchie at At&T Bell Labs.

    There are many applications and software that are programmed in C language. Not only that but also OS systems (Operating Systems) like Unix, DOS, and Windows are also written in C programming language.

    It is also one of the few languages to have international standard, ANSI C.


    Features of C

    • Simple and easy to learn.
    • Fast, Powerful & Efficient.
    • Procedural Language
    • Portable language.
    • Structured Programming Language
    • Rich Library.
    • Mid-Level Programming Language.
    • Pointers/Recursion.
    • Extensible

    Understand the features Individually.

    1. Simple and easy to learn.

    C is simple and easy to learn the language as it provides a structured Language approach (i.e. to break the problem into modules), its rich set of library functions, a simple set of keywords, data types, etc.

    2. Fast, Powerful & Efficient.

    The compilation and execution time of C language is fast as it provides powerful operators, variety of data types and it has a lesser inbuilt function and access to direct manipulation with the computer hardware hence makes it more efficient and the first choice for the programmers..

    3. Procedural Language

    As a procedural language means the language that follows, in order, a set of commands. And in C there are step by step, ordered predefined instructions that are carried out tat makes it procedural.

    4. Portable language.

    It is also known as Machine Independent Language that can be executed on different machines with particular changes, hence making it portable and Independent Programming Language.

    5. Structured Programming Language.

    C language is a structured programming language that makes the program debugging, testing, and maintenance easier. This makes users think of a problem in terms of function modules or blocks. The collection of these modules makes a complete program.

    6. Rich Library.

    C is rich in inbuilt function and Operators that make easier for the programmer to write a complex program easily and help in faster development.

    7. Mid-Level Programming Language.

    As we understand, that C is a low-level language but however, it also supports the high-level language. Therefore, it binds the gap between these low and high-level language, hence known as Mid-Level Language.

    A user can use C programming Language for System Programming that is writing Operating System and can be used as well as in  Application Programming that is for creating a menu-driven customer billing system.

    8. Pointers/Recursion.

    Pointers and Recursion provide certain functionality to the program.

    • Pointers allow us to directly interact with the memory and is used for function, array, structures, etc.
    • Recursion allows us to call the function within the function, providing the re-usability of every function.

    9. Extensible.

    Last but not the least feature/advantage of C is its ability to extend itself. C Language is easy to extend due to its ability to extend or add new features in already created applications.


    Application of C

    • C language is used for creating computer applications.
    • Used in writing Embedded software.
    • Firmware for various electronics, industrial and communications products which use micro-controllers.
    • It is also used in developing verification software, test c_Introduction, simulators etc. for various applications and hardware products.
    • For Creating Compiler of different Languages which can take input from other language and convert it into lower level machine dependent language.
    • It is used to implement different Operating System Operations. UNIX kernel is completely developed in C Language.

    Advantages of C

    1. C language is a building block for many other currently known languages. C language has a variety of data types and powerful operators. Due to this, programs written in the C language are efficient, fast and easy to understand.

    2. C is highly portable language. This means that C programs written for one computer can easily run on another computer without any change or by doing a little change.

    3. There are only 32 keywords in ANSI C and its strength lies in its built-in functions. Several standard functions are available which can be used for developing programs.

    4. Another important advantage of C is its ability to extend itself. A C program is basically a collection of functions that are supported by the C library this makes us easier to add our own functions to C library. Due to the availability of large number of functions, the programming task becomes simple.

    5. C language is a structured programming language. This makes users think of a problem in terms of function modules or blocks. The collection of these modules makes a complete program. This modular structure makes program debugging, testing, and maintenance easier.

    Disadvantages of C

    • C does not have the concept of OOPs, that’s why C++ is developed.
    • There is no runtime checking in the C language.
    • There is no strict type checking. For example, we can pass an integer value.
    • It doesn’t have the concept of a namespace.
    • It doesn’t have the concept of a constructor or destructor.

  • C – if…else statement

    If the Boolean expression is true then the code inside the if statement block is executed or if it is false then the code inside else statement will be executed. Hence if..else statement.

    Syntax

    Syntax of if...else statement in C Language:

     if (condition) 
     {
      //code executed if condition true 
     }
     else
     {
      //code executed if condition false 
     }

    If…else Flowchart:

    Example of if…else statement in C.

    #include <stdio.h>
    
    void main()
    {
      int num1, num2;
    
      num1 = 56;
      num2 = 89;
    
      if (num1 > num2)
      {
        printf("num1 is greater than num2y");
      }
      else
      {
        printf("num2 is greater than num1");
      }
    }

    The output of if…else statement in C.

    num2 is greater than num1


  • Features of C

    Features and advantages of C

    • Simple and easy to learn.
    • Fast, Powerful & Efficient.
    • Procedural Language
    • Portable language.
    • Structured Programming Language
    • Rich Library.
    • Mid-Level Programming Language.
    • Pointers/Recursion.
    • Extensible

    1. Simple and easy to learn.
    C is simple and easy to learn language as it provides a structured Language approach (i.e. to break the problem into modules), its rich set of library functions, a simple set of keywords, data types, etc.

    2. Fast, Powerful & Efficient.
    The compilation and execution time of C language is fast as it provides powerful operators, variety of data types and it has a lesser inbuilt function and access to direct manipulation with the computer hardware hence makes it more efficient and the first choice for the programmers..

    3. Procedural Language
    As a procedural language means the languagethat follows, in order, a set of commands. And in C there are step by step, ordered predefined instructions that are carried out tat makes it procedural.

    4. Portable language.
    It is also known as Machine Independent Language that can be executed on different machines with particular changes, hence making it portable and Independent Programming Language.

    5. Structured Programming Language.
    C language is a structured programming language that makes the program debugging, testing, and maintenance easier. This makes users to think of a problem in terms of function modules or blocks. The collection of these modules makes a complete program.

    6. Rich Library.
    C is rich in inbuilt function and Operators that make easier for the programmer to write a complex program easily and help in faster development.

    7. Mid-Level Programming Language.
    As we understand, that C is a low-level language but however it also supports the high level language. Therefore, it binds the gap between these low and high level language, hence known as Mid-Level Language.

    A user can use C programming Language for System Programming that is writing Operating System and can be used as well as in  Application Programming that is for creating a menu-driven customer billing system.

    8. Pointers/Recursion.
    Pointers and Recursion provides a certain functionality to the program.

    • Pointers allow us to directly interact with the memory and is used for function, array, structures, etc.
    • Recursion allows us to call the function within the function, providing the re-usability of every function.

    9. Extensible.
    Last but not the least feature/advantage of C is its ability to extend itself. C Language is easy to extend due to its ability to extend or add new features in already created applications.


    Disadvantage of C

    C does not have a concept of OOPs(Object-oriented programming), namespace, constructor or destructor.

  • C – nested if statements

    This statement allows the user to use if block inside the other if block. And the inner if statement is executed only if the outer if statement’s condition is true.

    Syntax

    Syntax of nested if statement in C:

    if(condition1)
     {    
        //block of code to be executed    
        if(condition2)
        {  
          //block of code to be executed    
        }    
     } 

    nested if Flowchart:

    nested if

    Example of nested if statement in C:

    #include <stdio.h>
    
    int main()
    {
      // local variable
      int num1 = 60;
      int num2 = 90;
    
      // first if statement
      if (num1 > 50)
      {
        // if inside if statement
        if (num2 > 80)
        {
          printf("Actual value of num1 is : %d\n", num1);
          printf("Actual value of num2 is : %d\n", num2);
        }
      }
    
      return 0;
    }

    The output of nested if statement in C.

    Actual value of num1 is : 60
    Actual value of num2 is : 90


  • Java – this Keyword

    In Java, this is a reference variable, this can be used inside any method or constructor to refer to the current object.

    Following demonstrating the use of this

    volume(double w, double h, double d) 
     {  
      this.width = w; 
      this.height = h; 
      this.depth = d;
     }  

    Use of this Keyword in constructor:

    class Student
     {
      String name;
      int marks;
    
      Student(String name, int marks)
      {
       this.name = name;   //use of this
       this.marks = marks; // use of this
      }
      void display()
      {
       System.out.println("Name: " + name + " marks:" + marks);
      }
     }
     public class main
     {
      public static void main (String[] args) 
      {
       Student st = new Student("Daniel", 90);
       st.display();
      }
     } 

    Output:

    Name: Daniel marks:90

    Notethat, Java does not allow to declare two local variables with the same name inside the same or enclosing scopes, so the use of the same parameter name and data-members(instance variable) is possible because of this operator.
    this keyword used within the constructor refers to the instance variable of that constructor or class.

    In the above example, this.name = name, this.name refers to the instance variable whereas the name on the right side refers to the parameter value. and equal(=) sign assign parameter value to an instance variable. Also called Instance Variable Hiding.

    If we do not use this keyword violating the Java declaration process, we get the following result:

    class Student
     {
      String name;
      int marks;
    
      Student(String name, int marks)
      {
       name = name;   //not using of this
       marks = marks; //not using of this
      }
      void display()
      {
       System.out.println("Name: " + name + " marks:" + marks);
      }
     }
     public class main
     {
      public static void main (String[] args) 
      {
       Student st = new Student("Daniel", 90);
       st.display();
      }
     }

    Output:

    Name: null marks:0


    this Keyword: to pass as an argument in the method:

    class Method
     {
      void m1(Method obj)
      {
       System.out.println("This is method m1");
      }
      void m2()
      {
       m1(this);
      }
     }
     class Main
     {
      public static void main (String[] args) 
      {
       Method m = new Method();
       m.m2();
      }
     }

    Output:

    This is method m1


    this: Invoke current class method:

    The method of the current class can be invoked by using this keyword. If this keyword is not used then the compiler automatically adds this keyword while invoking the method.

    source code:

     class Method
     {
      void m1()
      {
       System.out.println("This is method m1");
      }
      void m2()
      {
       System.out.println("This is method m2");
       this.m1();
      }
     }
     class Main
     {
      public static void main (String[] args) 
      {
       Method m = new Method();
       m.m2();
      }
     }

    Output:

    This is method m2
    This is method m1


  • Java – StringBuffer

    StringBuffer and StringBuilder in java is a class that provides the mutable(changeable) ability.
    Since a String is immutable that is its value cannot be changed once the object is created. So to modify the String, StringBuffer and StringBuilder class is used.

    Both these classes work fine but the difference is that the StringBuffer is thread-safe whereas StringBuilder is not.

    • Far a faster process, consider using StringBuilder because it is faster than StringBuffer.
    • For safety, purposes consider using StringBuilder.

    StringBuffer Methods:

    1. StringBuffer append() method:

    This method concatenates the two string and updates the result. The method takes boolean, char, int, long, Strings, etc.

    Example for StringBuffer append() in Java:

     public class StringBufferTest
      {  
       public static void main(String args[])
       {  
        StringBuffer s =  new StringBuffer("Long ");  
        s.append("Day");//changed with Day  
        System.out.println(s);//prints the concatenated result  
       }  
      }

    Output:

     Long Day

    2. StringBuffer insert() method:

    This String inserts the new string in a specified position. We need to offset the position before the value as shown in an example.

    Example for StringBuffer insert() in Java:

     public class StringBufferTest
      {  
      public static void main(String args[])
      {  
        StringBuffer s = new StringBuffer("Long ");  
        s.insert(1,"Day");//now original string is changed  
    
        System.out.println(s);//prints HJavaello  
      }  
      }

    Output:

     LDayong 

    3. StringBuffer delete() method:

    As the name suggest, this method is used to remove/delete the string by index number. We need to specify the beginIndex and endIndex.

    Example for StringBuffer delete() in Java:

     public class StringBufferTest 
      {
      public static void main(String args[]) 
      {
        StringBuffer s = new StringBuffer("ABCDEFGHIJK");
        s.delete(4, 8); 
    
        System.out.println(s); 
      }  
      }

    Output:

    ABCDIJK

    4. StringBuffer replace() method:

    This method is used to replace a String with another String within a specified index.

    This content three values one to remove from beginIndex to endIndex and then the String value for replacement.

    Example for StringBuffer replace() in Java:

     public class StringBufferTest 
      {
       public static void main(String args[]) 
       {
         StringBuffer s = new StringBuffer("ABCDEFGHIJKJ");
         s.replace(4, 9, "xyz");
    
         System.out.println(s); 
       }  
      }

    Output:

     ABCDxyzJKJ 

    5. StringBuffer reverse() method:

    This method reverses the value of the string that is invoked.

    Example for StringBuffer reverse() in Java:

     public class StringBufferTest 
     {
      public static void main(String args[])
      {
       StringBuffer s = new StringBuffer("Sting Buffer");
       s.reverse();
    
       System.out.println(s);
      }  
     }

    Output:

     reffuB gnirtS 

    List of some other methods that are similar to string class:

    1. void ensureCapacity(int minimumCapacity):
      This method ensures that the buffer capacity is at least to minimum capacity.
    2. int capacity():
      It returns the current capacity of the string buffer.
    3. int indexOf(String str):
      The index of the first occurrence of the specified substring is returned within this string.
    4. int indexOf(String str, int fromIndex):
      The index of the first occurrence of the specified substring is returned within this string and it starts from the index specified.
    5. int lastIndexOf(String str, int fromIndex):
      The index of the last occurrence of the specified substring is returned within this string and from the specified index.
    6. void setLength(int newLength):
      This method sets the length of the string buffer.
    7. int length():
      It is used to return the length of the string buffer.
    8. String toString():
      The data represented to this string buffer is converted to a string through this method
    9. char charAt(int index):
      It returns the sequence currently represented by the string buffer that is specified the index argument.
    10. CharSequence subSequence(int start, int end):
      This method returns a new character sequence that is a sub-part of this sequence.

    There are more String methods such as, String substring(int start, int end),  String substring(int start),  void setCharAt(int index, char ch), int lastIndexOf(String str), void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin).