A loop in C programming is a control flow structure that allows you to repeat a block of code multiple times until a specific condition is met.
Loop Consists three points:
In for loop first it check condition and then if the condition is satisfy then its body part is execute and then updation is happen.at last if condition false and loop will terminate.
Syntaxfor( initial value; condition; incrementation or decrementation ) { //statement //statement }Components
#include<stdio.h> int main() { int x=10,i; for(i=0;i<=x;i++) { printf("%d\t",i); } }Output:
0 1 2 3 4 5 6 7 8 9 10
In first time at i=0 then it check condition and then if the condition is satisfy then its body part is execute and then updation is happen.at last at x=11 condition false and loop is terminate.
In while loop first it checks the condition and body part execute and then updation is happen.At last if condition is false and loop will terminate.
Syntaxwhile(condition) { //statement //statement incrementation or decrementation; }Example
#include<stdio.h> int main() { int x=10,i=0; while(i<x) { printf("%d\t",i); i++; } }Output
0 1 2 3 4 5 6 7 8 9 10
Here the initially x=10 and i=0 first it check the condition and then body part execute then updation is happen.At last at i=11 condition is false and loop will terminate.
In do-while loop first body part execute then updation is happen after that condition checked.
Syntaxdo{ //statement //statement incrementation or decrementation; }while( condition );Example
#include<stdio.h> int main() { int x=10,i=0; do{ printf("%d",i); }while(i<=10); }Output:
0 1 2 3 4 5 6 7 8 9 10 11
Here the initially x=10 and i=0 first body part execute then updation is happen after that condition checked.
S.No | for | while | do-while |
---|---|---|---|
1. | for loop is known as entry controlled loop. | while loop is known as entry controlled loop. | do-while loop is known as exit controlled loop. |
2. | Syntax: for(initialization; condition;updating) { // Statements } | Syntax: while(condition) { // Statements } |
Syntax: do { //Statements; } While(condition); |
3. | Initialization and updating is the part of the syntax. | Initialization and updating is not the part of the syntax. | Initialization and updating is not the part of the syntax. |
4. | There is no semicolon ';' after the condition in the syntax of the for loop. | There is no semicolon ';' after the condition in the syntax of the while loop. | There is semicolon ';' after the condition in the syntax of the do while loop. |
5. | If the condition is not true first time than control will never enter in a loop. | If the condition is not true first time than control will never enter in a loop. | Even if the condition is not true for the first time the control will enter in a loop. |