C Loops


Loops can execute a block of code a number of times.


Different Kinds of Loops

  • for - loops through a block of code a number of times.
  • while - loops through a block of code while a specified condition is true.
  • do/while - also loops through a block of code while a specified condition is true.

The for loop

The for loop in C language is also used to iterate the statement or a part of the program several times.

But, we can initialize and increment or decrement the variable also at the time of checking the condition in for loop.

Syntax

for(initialization;condition;incr/decr){  
//code to be executed  
}

Example

#include <stdio.h>      
#include <conio.h>      
void main(){      
int i;    
clrscr();      
    
for(i=1;i<=5;i++){    
printf("%d \n",i);    
}   
      
getch();      
}      
Output
1
2
3
4
5

The while loop

The while loop in C language is used to iterate the part of program or statements many times.

Syntax

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

Examole

#include <stdio.h>      
#include <conio.h>      
void main(){      
int i=1;    
clrscr();      
    
while(i<=5){    
printf("%d \n",i);    
i++;    
}   
      
getch();      
}
Output
1
2
3
4
5

The do while loop

To execute a part of program or code several times, we can use do-while loop of C language. The code given between the do and while block will be executed until condition is true.

Syntax

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

Example

#include <stdio.h>    
#include <conio.h>    
void main(){    
int i=1;  
clrscr();    
  
do{  
printf("%d \n",i);  
i++;  
}while(i<=5);  
    
getch();    
}   
Output
1
2
3
4
5

Share this article on