7.2. do-while Program Loops
C# provides a third loop variation that you can add to your loop toolkit called a do-while loop. The syntax for a do-while loop is as follows:
do
{
// do-while statement block
} while (expression2);
The do-while loop variant is similar to the while loop with one major exception: A do-while loop always makes at least one pass through the loop statement block. If you look at the other two loop variations, the test of expression2 takes place before the loop statement block. With the for and while loop statements, it is quite possible for expression2 to evaluate to logic False at the very start of the loop. If expression2 is false for either the for or while loop, no pass is made through the statements in the loop body.
This is not true for a do-while loop. A do-while loop always makes at least one pass through its statement block. This is because the expression that evaluates whether another pass should be made through the loop is made at the bottom of the loop, and is arrived at after the statements in the loop body have been executed at least once. In other words, program control has to pass through the do-while statement block at least one time.
Try It Out: Generate Random NumbersC# provides a class that is capable of generating a series of random numbers. Let's write a program that tests whether that class generates a series of random numbers wherein two identical random numbers are produced "back to back." Listing 7-3 shows the code for the program. ... |
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access