C Loops

The loops in C language are used to execute a block of statements or a part of the program several times. In other words, it iterates a code or group of code many times.

Advantage of loops in C

> It reduce code length.
> It helps to traverse the elements of array.

Types of C Loops

There are three types of loops in C language it is given below:
  • do while
  • while
  • for
  • do-while loop in C

    It iterates the code until condition is false. Here, condition is given after the code. So at least once, code is executed whether condition is true or false
    It is better if you have to execute the code at least once.
    The syntax of do-while loop in c language is given below:

    do  {  
       //code to be executed  
      }   while(condition); 
    

    Flowchart of do while loop


    while loop in C

    Like do while, it iterates the code until condition is false. Here, condition is given before the code. So code may be executed 0 or more times. It is better if number of iteration is not known by the user.
    The syntax of while loop in c language is given below:

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

    When use while loop in C

    The C language while loop should be used if number of iteration is uncertain or unknown.

    Flowchart of while loop in C

    Example of while loop in C language

    Let's see the simple program of while loop that prints:
    #include <stdio.h>
    void main( ) {      
    int i = 1;     
    while(i<=8){    
    printf("%d ",i);    
    i++;    
     }   
     } 
     Output: 1 2 3 4 5 6 7 8  
    

    Program to print table for the given number using while loop in C

    #include <stdio.h>
    void main() {    
    int i = 1,number = 0;      
    printf("Enter a number: ");  
    scanf("%d",&number);  
    while(i<= 10) {  
    printf("%d ",(number*i));  
    i++;  
     }  
     }
    Output:
    Enter a number:10   
    10  20  30  40  50  60  70  80  90  100
    

    Infinitive while loop in C

    if you pass 1 as a expression in while loop, it will run infinite number of times.

    while(1){  
       //statement  
    }