Do while loop in C with examples

Do while loop in C with examples

Do while loop in C is very similar to while loop of C. But only the difference is that in C while loop, first condition is checked then statement inside the while loop is executed by in the do-while loop of C, first statement is executed means operations first performed and then check conditions.

We can also defined is as it is a exit controlled loop which is necessary in some occasions where first we need to execute the body of the loop before the test is performed, such situations can be handle with the help of a do-while statement.

In do-while loop in c statements, its body is executed at least once.

Example 1: Do while loop in C

[c] #include<stdio.h> #include<conio.h> void main() { int a=1; do { printf("%d\t",a); a++; } while(a&lt;=10); getch(); } [/c]

Output

AS in the above example we can see that first we have initialized the value of a by 1 and then we printed the value of a and after the printing value of a we have then increment the value of a by one and at last we have tested the condition a<=10.

Example 2 : C Program to print even number

[c] #include<stdio.h> #include<conio.h> void main() { int a=2; do { printf("%d\t",a); a=a+2; } while(a<=10); getch(); } [/c]

Output

This example is also very similar to the above example. but the difference is that here we are increasing the value of a by 2 each time. So while loop will be executed only 5 times.

In real-world we use do while loop in c for the cases where we want to print first our output then we do check the while condition loops. It is very rarely used.