C Language | Flow Control | do-while Statement
This article explains the do statement, which checks whether to repeat a statement after executing it. Unlike a while statement, a do statement always executes its body at least once regardless of the condition.
Looping with a Delayed Condition Check
A while statement evaluates its condition before executing the repeated statement and decides whether to continue the loop. In contrast, a do statement evaluates its condition after executing the statement.
do Statement
do statement while (condition);
Except for executing the repeated statement first, a do statement is basically the same as a while statement. Because a while statement evaluates the condition before running the loop, it skips the body entirely if the first evaluation is false. A do statement is useful when the body must run at least once regardless of the condition.
Code 1
#include <stdio.h>
int main()
{
int iCount = 1 , iMax;
printf("반복 횟수를 입력하십시오. >");
scanf("%d" , &iMax);
do {
printf("%d번째 루프입니다.\n" , iCount++);
} while (iCount <= iMax);
return 0;
}
Code 1 reads a repetition count and repeats the statement with a do loop. The major difference from a while statement is that the body executes once even if iCount <= iMax is false. Even if the input value is negative or 0, the do statement executes its body once because it checks the condition afterward.
Outside of special cases, do statements are not used often. However, you may encounter one when reading code written by someone else, and some algorithms can be expressed more clearly with a do statement. It is worth remembering.