Loops can execute a block of code a number of times.
Different Kinds of Loops
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.
for(initialization;condition;incr/decr){ //code to be executed }
#include <stdio.h> #include <conio.h> void main(){ int i; clrscr(); for(i=1;i<=5;i++){ printf("%d \n",i); } getch(); }
1 2 3 4 5
The while loop in C language is used to iterate the part of program or statements many times.
while(condition){ //code to be executed }
#include <stdio.h> #include <conio.h> void main(){ int i=1; clrscr(); while(i<=5){ printf("%d \n",i); i++; } getch(); }
1 2 3 4 5
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.
do{ //code to be executed }while(condition);
#include <stdio.h> #include <conio.h> void main(){ int i=1; clrscr(); do{ printf("%d \n",i); i++; }while(i<=5); getch(); }
1 2 3 4 5