Author: admin

  • C – Loops

    There may be times in a program where a block of code needs to be executed several times sequentially. In such cases, Loops are used to execute a sequence of statements many times until the stated condition becomes false.

    Loops in C programming
    Loops in C Programming

    Two Types of Loops in C Programming.

    1. Entry controlled loop:

    In this type loop, the stated conditional is checked first and then the block of code is executed. It is also called a pre-checking loop.

    There are two types of entry control loop:

    • for loop. 
    • while loop.

    2. Exit controlled loop:

    In this type loop, the block of code is executed first and then the condition is checked. It is also called a post-checking loop.

    There is only one type loop in the exit control loop.

    • do-while loop.

    While Loop in C

    A while loop is a straight forward loop and is also an entry-control loop. It evaluates the condition before executing the block of the loop. If the condition is found to be true, only then the body of the loop is executed.

    The loop continues until the condition stated found to be false.

    While Loop in C

    Syntax of While Loop in C.

     while(condition)
      {  
        //block of code to be executed  
      } 

    2. do-while loop in C:

    do-while loop in C is just as same as while loop, only difference is that in do-while the condition is always executed after the loop as shown in syntax below.

    Unlike while loop, where the body of the loop is executed only if the condition stated is true but in the do-while loop, the body of the loop is executed at least once. do-while is an exit-control loop that is it checks the condition after the first execution of the block.

    do-while loop in C

    Syntax of do-while Loop in C.

    do
     {
       //statements..
     }while (condition);

    3. for Loop in C

    In C programming, for loop is a more efficient loop structure and is an entry-control loop. The iteration continues until the stated condition becomes false.

    It has three computing steps as shown in the syntax below.

    • initialization: The first step is the initialization of the variable and is executed only once. And need to end with a semicolon(;).
    • condition: Second is condition check, it checks for a boolean expression. If true then enter the block and if false exit the loop. And need to end with a semicolon(;).
    • Increment or Decrement: The third one is increment or decrement of the variable for the next iteration. Here, we need to use the semicolon(;).
    for loop in C

    Syntax of for loop in C

     for(initialization; condition; Increment or Decrement) 
     {
      // Statements
     } 

    The Infinite Loop

    As the name suggests, the infinite loop is a forever executing loop. The infinite loop repeats indefinitely and never terminates. It means the condition never turns to false. It is also known as an indefinite loop or an endless loop.

    We can use one of the Loops in C to turn it into infinite loop.

    infinite ‘for’ loop

    for(; ;)  
    {  
      //body of the loop  
    }

    Example:

    #include <stdio.h>
     
    int main () 
    {
    //condition for infinite
       for( ; ; ) 
       {
          printf("INFINITE LOOP.\n");
       }
    
       return 0;
    }

    If the above program is executed then we will get infinite printf statement. The compiler assume the condition to be true if the condition is absent in the loop.

    NOTE: You can terminate an infinite loop by pressing Ctrl + C keys

    We can also create infinite while loop by defining the condition as shown below.

    while(1)  
    {  
       //body of the loop  
    } 

    infinite do-while loop

    do  
    {  
      //body of the loop  
    }while(1);

  • C – switch statement

    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

    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;    
      }

    Switch statement Flowchart:

    switch statement

    Example of switch statement in C.

    #include <stdio.h>
    
    int main()
    {
      //local variable definition
      char grade = 'D';
    
      switch (grade)
      {
        case 'A':
          printf("Excellent!\n");
          break;
        case 'B':
          printf("Very Good!\n");
          break;
        case 'C':
          printf("Well done\n");
          break;
        case 'D':
          printf("GRADE D\n");
          break;
        case 'F':
          printf("Better try again\n");
          break;
        default:
          printf("Invalid grade\n");
      }
    
      printf("You Pass with Grade: %c\n", grade);
    
      return 0;
    }

    The output of the switch statement in C.

    GRADE D
    You Pass with Grade: D


  • C – nested switch statement

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

    Syntax

    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 */
    }

    Example of nested switch statements in C:

    #include <stdio.h>
    
    int main()
    {
      //local variable
      int a = 10;
      int b = 20;
    
      switch (a)
      {
        case 10:
          printf("The OUTER Switch.\n", a);
    
          //INNER Switch
          switch (b)
          {
            case 20:
              printf("The INNER Switch.\n", a);
          }
      }
    
      return 0;
    }

    The output of nested switch statements in C.

    The OUTER Switch.
    The INNER Switch.


  • C – if statement

    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

    Syntax of if statement in C:

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

    if statement Flowchart:

    if statement

    Example of if statement in C Program:

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

    The output of if statement in C.

    num1 is greater than num2


  • 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