C – do while loop in C programming with example



C – do while loop in C programming with example






In the previous tutorial we learned while loop in C. A do while loop is similar to while loop with one exception that it executes the statements inside the body of do-while before checking the condition. On the other hand in the while loop, first the condition is checked and then the statements in while loop are executed. So you can say that if a condition is false at the first place then the do while would run once, however the while loop would not run at all.

C – do..while loop

Syntax of do-while loop
do
{
//Statements

}while(condition test);

Flow diagram of do while loop

Example of do while loop

#include <stdio.h>
int main()
{
int j=0;
do
{
printf
("Value of variable j is: %d\n", j);
j
++;
}while (j<=3);
return 0;
}
Output:
Value of variable j is: 0
Value of variable j is: 1
Value of variable j is: 2
Value of variable j is: 3

While vs do..while loop in C

Using while loop:
#include <stdio.h>
int main()
{
int i=0;
while(i==1)
{
printf
("while vs do-while");
}
printf
("Out of loop");
}
Output:
Out of loop
Same example using do-while loop
#include <stdio.h>
int main()
{
int i=0;
do
{
printf
("while vs do-while\n");
}while(i==1);
printf
("Out of loop");
}
Output:
while vs do-while
Out of loop
Explanation: As I mentioned in the beginning of this guide that do-while runs at least once even if the condition is false because the condition is evaluated, after the execution of the body of loop.

Post a Comment

Previous Post Next Post