do-while
Loop
In the for
Loop chapter we saw the steps in which the while
loop is executed:
preparation condition check actual work iteration condition check actual work iteration ...
The do-while
loop is very similar to the while
loop. The difference is that the condition check is performed at the end of each iteration of the do-while
loop, so that the actual work is performed at least once:
preparation actual work iteration condition check ← at the end of the iteration actual work iteration condition check ← at the end of the iteration ...
For example, do-while
may be more natural in the following program where the user guesses a number, as the user must guess at least once so that the number can be compared:
import std.stdio; import std.random; void main() { int number = uniform(1, 101); writeln("I am thinking of a number between 1 and 100."); int guess; do { write("What is your guess? "); readf(" %s", &guess); if (number < guess) { write("My number is less than that. "); } else if (number > guess) { write("My number is greater than that. "); } } while (guess != number); writeln("Correct!"); }
The function uniform()
that is used in the program is a part of the std.random
module. It returns a random number in the specified range. The way it is used above, the second number is considered to be outside of the range. In other words, uniform()
would not return 101 for that call.
Exercise
Write a program that plays the same game but have the program do the guessing. If the program is written correctly, it should be able to guess the user's number in at most 7 tries.