How does the do…while Loop works?
The working of the do…while loop is explained below:
- When the program control first comes to the do…while loop, the body of the loop is executed first and then the test condition/expression is checked, unlike other loops where the test condition is checked first. Due to this property, the do…while loop is also called exit controlled or post-tested loop.
- When the test condition is evaluated as true, the program control goes to the start of the loop and the body is executed once more.
- The above process repeats till the test condition is true.
- When the test condition is evaluated as false, the program controls move on to the next statements after the do…while loop.
As with the while loop in C, initialization and updation is not a part of the do…while loop syntax. We have to do that explicitly before and in the loop respectively.
The flowchart below shows the visual representation of the flow of the do…while loop in C.
do…while Loop in C
Loops in C language are the control flow statements that are used to repeat some part of the code till the given condition is satisfied. The do-while loop is one of the three loop statements in C, the others being while loop and for loop. It is mainly used to traverse arrays, vectors, and other data structures.