Example of do while loop
//print 1 2 3 4 5 6 7 8 9 10
#include<stdio.h>
int main()
{
int i=1;
do{ printf(“%d\n”,i);
i++;
}
while(i<=10); return 0;
}
OUTPUT:-
1
2
3
4
5
6
7
8
9
10
Example of while loop
//print 1 2 3 4 5 6 7 8 9 10 .
#include<stdio.h>
int main()
{
int i=1;
while(i<=100000){
printf(“%d\n”,i);
i++;
}
return 0;
}
OUTPUT:-
1
2
3
4
5
6
7
8
9
10
Difference between while loop and do while loop
1 .Evaluation of Condition:
- In a while loop, the condition is evaluated before the execution of the loop’s body. If the condition is initially false, the loop body may not execute at all.
- In a do-while loop, the condition is evaluated after the execution of the loop’s body. This guarantees that the loop body will be executed at least once, regardless of the initial condition.
2 .Minimum Execution:
- A while loop may not execute its body at all if the condition is false initially.
- A do-while loop always executes its body at least once, regardless of the initial condition.
3 .Usability:
- While loops are typically used when the number of iterations is uncertain and the loop body should execute zero or more times.
- Do-while loops are useful when you want to ensure that the loop body is executed at least once, such as in situations where you need to validate user input or perform initialization before checking a condition.