It often needs to repeat a piece of program as a condition is true (such as the precision of a calculation is insufficient). C offers the following two structures for this:
The do-while statement lets you repeat a statement or compound statement until a specified expression becomes false.
The expression in a do-while statement is evaluated after the body of the loop is executed. Therefore, the body of the loop is always executed at least once.
The expression must have arithmetic or pointer type. Execution proceeds as follows:
- The statement body is executed.
- Next, expression is evaluated. If expression is false, the do-while statement terminates and control passes to the next statement in the program. If expression is true (nonzero), the process is repeated, beginning with step 1.
The do-while statement can also terminate when a break, goto, or return statement is executed within the statement body.
Code:
while (condition) (/ * 1 structure: a condition for entering the code * /
repeating instructions;
)
do (/ * structure 2: a condition for the release of the code * /
repeating instructions;
) While (condition);
The block between the bracket {} is repeated in both cases as long as the conditions is true. In the case of the first structure, the condition is evaluated first, so it is possible (if the condition is false from the outset) that the instructions are not executed at all. The second structure is known, however, that the instructions will be executed at least once, since the condition is evaluated at the end of each repetition.
Bookmarks