C do-while loop

A do-while loop is a post tested loop. A do-while loop statement is used when user wants to execute the loop block at least once, no matter what initial condition of the test expression is. The loop always ends with a semicolon(;).

Syntax of do-while loop:

Working of do-while loop:

  • There is a minor difference between the working of while and do-while loops.
  • In while loop, a condition is tested before executing any statements within the while loop.
  • As against this, do-while loop tests the condition after executing the statements within the loop.
  • That means, the statements inside loop body would execute at least once, even if the condition fails for the first time.

Example:

Output:

As we have declared the value of i=1, which is called initialization. Firstly, the value of i is print, then the condition is checked. The while loop condition is true i.e. 1 < 5. It prints the value of ‘i’ as shown in the output.
Next increment i by one i.e. i=2. Again the condition will check, 2 <5. And it will continue up to the condition is false.

Flowchart of do-while loop:

The flowchart of the do-while loop shown below would help you to understand the operation of the do-while loop.

do-while loop

Help others by sharing the content!

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.