do-while Loop in C
For Complete YouTube Video: Click Here
Here we will try to understand the do-while Loop in C.
We have already covered While Loop in C.
Table of Contents
do-while Loop in C
The do-while loop is the same as that of the while loop.
The main difference between the while and do-while loop is that the do-while loop body is executed at least once.
The while loop body may not be executed at least once.
do-while Loop Syntax
The image below is the syntax for the do-while loop.
In the above image, do is the keyword.
Below the do are the open and closing flower braces for the loop body.
The statements to be executed are placed in the loop’s body.
Besides, the closing flower braces are the while statement with the control statement.
The above syntax clearly shows that the loop’s body is executed at least once, and then the controlling expression in the while statement will be executed.
If the controlling expression evaluates to be false, the loop’s body will not be executed further. Else the loop’s body will be executed.
Whereas in a while loop, if the controlling expression evaluates to false in the first iteration, the loop’s body will not be executed.
do-while Loop Example
The image below is an example of a do-while loop.
In the above example, we have assigned the value of ‘i’ as 0.
In the do-while loop, the loop’s body is executed first, and then the controlling expression in the while statement will be executed.
In our case, the controlling expression evaluates to false as the value of i is not equal to 0.
So the body of the loop will not be executed further.
While vs. Do-while Loop
The image below is the same example written using a while loop.
As the value of i is not equal to 1, the loop’s body will not be executed.