header

Do-While Loop Example

Consider a simple program where you enter an integer value in the range 1 to 1000 and the program displays how many tries it took to guess your number. The program uses these variables:

A do-while loop is appropriate for this program because we know the program must make at least one guess. That is, we know ahead of time that the body of the loop will be executed at least once. The graphic below illustrates just the processing logic; the input of v and the output of n is not shown.

The number of guesses, n, is initialized with a value of 0 because, initially, the program hasn't made any guesses yet. Each time through the loop, the program makes another guess. Consequently, each time through the loop the number of guesses in incremented by one. The program's guessing strategy is simple. The first guess is 1, the second guess is 2, the third guess is 3, and so on. Eventually it will guess the value entered by the user. As long as the program's guess is not equal to the value entered by the user, the program will make another guess. This algorithm is known as a linear search algorithm.

The table below illustrates a sample run of this program where the user entered a value of 5.

Action v n g Comment
  5 ? ? Initial values after input.
Execute: n = 0 5 0 ? Initialize the number of guesses.
Execute: n = n + 1 5 1 ? Add one to the number of guesses.
Execute: g = n 5 1 1 The first guess is 1.
Test: g != v 5 1 1 Test condition is true.
Execute: n = n + 1 5 2 1 Add one to the number of guesses.
Execute: g = n 5 2 2 The second guess is 2.
Test: g != v 5 2 2 Test condition is true.
Execute: n = n + 1 5 3 2 Add one to the number of guesses.
Execute: g = n 5 3 3 The third guess is 3.
Test: g != v 5 3 3 Test condition is true.
Execute: n = n + 1 5 4 3 Add one to the number of guesses.
Execute: g = n 5 4 4 The fourth guess is 4.
Test: g != v 5 4 4 Test condition is true.
Execute: n = n + 1 5 5 4 Add one to the number of guesses.
Execute: g = n 5 5 5 The fifth guess is 5.
Test: g != v 5 5 5 Test condition is false.

When the test condition becomes false, the loop will terminate and the final number of guesses, 5, will be displayed.