While writing a program, there may be a situation when you need to repeat a block of code again and again up to certain number of times or up to infinity. In such situation, you would need to write loop statements. Loop is also known as iteration.
Advantages of Loops
In C-Language, there are 3 types of loops available:
For loop iterates the code until the condition is false. For loop uses initialization, and increment/decrement at the time of checking the condition.
Example 1: WAP to print counting 1 to 10 using For Loop. 1
#include<stdio.h> int main() { int i; //for(initialization; condition; inc/dec) for(i=1; i<=10; i++) { printf("For Loop %d ",i); } return 0; }
For loop is useful when the number of iteration is known to the user.
In While loop, initialization statement appears before the while loop begins, condition appears to test the loop, increment/decrement statement will appear inside the while loop to change the variable value for the next iteration. It is better if number of iterations is not known by the user.
Example 2: WAP to print counting 1 to 10 using While Loop. 1
#include<stdio.h> int main() { int i=1; //initialization while(i<=10) //condition { printf("While Loop %d ",i); i++; //increment } return 0; }
While loop is use where number of iteration is not known by the user.
Do while loop is similar to while loop, only the different is that the condition appears in the end. So, the code is executed at least once, even if the condition is false in the beginning.
Example 3: WAP to print counting 1 to 10 using Do While Loop. 1
#include<stdio.h> int main() { int i=1; //initialization do { printf("Do while loop %d ",i); i++; //increment }while(i<=10); //condition return 0; }
Do while loop is used where you want to execute the code at least once.
S.No. | While loop | Do while loop |
---|---|---|
In while loop, condition appears at the beginning of the loop. | In do while loop, condition appears at the end of the loop. | |
While loop statement will not execute if the condition is false at the first iteration. | Do while loop statement will execute at least once even if the condition is false at the first iteration. | |
Semicolon (;) is not required to terminate the while loop. | Semicolon (;) is required to terminate the do while loop. |
Example 4: WAP to explain the use of While Loop. 1
#include<stdio.h> int main() { int n=1; //initialization while(n!=0) { printf("\nEnter Number (0-exit)"); scanf("%d",&n); } return 0; }
If you pass 1 as an expression or any value other than 0, then the condition is true, 0 means false.
Example 5: Infinitive while loop.
int i=1; while(1) { printf("%d",i++); }
Example 6: Infinitive do while loop
int i=1; do { printf("%d",i++); }while(1);
Example 7: Infinitive for loop
int i=1; for(;;) { printf("%d",i++); }