Thursday, November 20, 2025

Loops in C. for, while and do.. while

 

Loops in C are control flow statements that facilitate the repeated execution of a block of code based on a specified condition. C provides three primary types of loops: for loop, while loop and do-while loop.

 

for loop

Simple for loop


  Syntax 

       for(initial value; condition; increment/decrement)

       {             

          statements;

       }

 

The for statement followed three statements in the parenthesis separated by semi-colon (;).

Initialization of the variables to execute once.

Conditional statement: It will check the condition, if it is true then body part of the loop will be executed.

Increment/decrement statements: After the condition check, increment/decrement statement is executed and once again the condition is evaluated.


Ex.

     int i;
     for(i=1;i<=10;++i)
           printf("%3d",i);


output 1  2  3  4  5  6  7  8  9  10  





Nested loop

 Loop in loop is called nested loop

  

Syntax   

       for(initial value; condition; increment/decrement)

              for(initial value; condition; increment/decrement)

                        statement;




   while
 
The while is an entry controlled loop. The condition is evaluated and if the condition is true then the executed of the loop.                     
                                             
Syntax

   ------------                          
   while(condition)                         
   {                                          
         statement 1;             
         statement 2;             
         -----------                     
         statement n;             
   }                                          
    --------------                                  
 
 
Ex.
   
         int i=1;
        while(i<=10)
        {
           printf("%3d",i);
           ++i;
        }


         output 1  2  3  4  5  6  7  8  9  10 


do - while

  The do while is exit controlled loop. The program proceeds to execute the body of the loop first. At the end of the loop, condition is teste. It is true then executed once again.
                                  

Syntax
           
  -------------
  do
   {                                          
         statement 1;             
         statement 2;             
         -----------                     
         statement n; 
   }while(condition);
    -----------------                              
 

 Ex.
     
        int i=1;
        do
        {
               printf("%3d",i);
               ++i;
        }while(i<=10)

        output 1  2  3  4  5  6  7  8  9  10 



 


No comments:

Post a Comment