The do-while Loop Statement


The do-while Loop Statement

The do-while loop is analogous to the while loop in that the loop body is repeatedly executed over and over again as long as the Boolean expression is true. However, there is one important difference the loop body, located between the keywords do and while (see Syntax Box 9.2), is executed before the Boolean expression is evaluated. Consequently, the loop body of the do-while loop is always executed at least once, even if the Boolean expression is false initially.

Syntax Box 9.2 The do-while Statement

 do_while_statement:=      do        <Loop_body>      while (<Loop_condition>); 


 <Loop_body>::= <Statement>;            ::= <Compound_statement> <Loop_condition>::= <Boolean expression> 


  • The <Loop_body> is repeated as long as <Loop_condition> is true.

A loop construct, such as the do-while loop, that has its loop condition at the end of the loop is called an exit condition loop.



The choice between the while loop and the do-while loop depends on the computational problem at hand. However, for the majority of the cases, the entry condition while loop is the correct choice. For example, if the loop is used to traverse a list of numbers (or a list of any other kind of objects), the list might well be empty, in which case the loop statements should never be executed. Thus, a do-while loop applied here would lead to flawed code.

Even though not as commonly called for as the while-loop, the do-while loop is highly compatible with a few distinct types of computational problems. One such problem is found in program parts that requests, receives, processes and evaluates user input repeatedly. Often the user input is used in the loop condition. In this scenario the user input must be received before it can be utilized here; in other words, the loop body, which fetches the user input, must be executed before the loop condition can be evaluated. This fits perfectly well with our exit condition do-while loop.

Listing 9.3 is used to illustrate this point. It contains the source code of a letter-guessing game. The program randomly picks a letter between A and Z; the aim of the game is to find the secret letter simply by typing in single letters. To help the player (the user) along, the program will let him or her know whether the secret letter is earlier or later in the alphabet than each guess. In the sample output after Listing 9.3, the secret letter was N and was found after the fifth guess, but this will vary between different games.

Listing 9.3 AlphabetGame.cs
01: using System; 02: 03: class AlphabetGame 04: { 05:     public static void Main() 06:     { 07:         string secretLetter; 08:         string letterGuess; 09:         Random Randomizer = new Random(); 10:          // Choose the secretLetter randomly from the full 11:          // alphabet ranging from Unicode 65 (reprenting 'A') to 12:          // Unicode 91 (representing 'Z') 13:         secretLetter = ((char)Randomizer.Next(65, 91)).ToString(); 14:         Console.WriteLine("Guess my secret letter\n" + 15:             "I will tell you if the secret letter\n" + 16:             "is Earlier or Later in the alphabet than your guess"); 17:         do 18:         { 19:             letterGuess = Console.ReadLine().ToUpper(); 20:              // Is secretLetter earlier or later than letterGuess? 21:             if (secretLetter.CompareTo(letterGuess) < 0) 22:                 Console.WriteLine("   Earlier\n"); 23:             if (secretLetter.CompareTo(letterGuess) > 0) 24:                 Console.WriteLine("   Later\n"); 25:         } while (secretLetter != letterGuess); 26:         Console.WriteLine("You got it!\n\nEnd of Game"); 27:     } 28: }  Guess my secret letter I will tell you if the secret letter is Earlier or Later in the alphabet than your guess M<enter>      Later S<enter>      Earlier P<enter>      Earlier O<enter>      Earlier N<enter> You got it! End of Game.  

The first part of line 9, before the assignment operator, declares Randomizer to hold a reference to an object of type System.Random. The latter half applies the keyword new to create a new object of type System.Random, which is then assigned to Randomizer, enabling it to generate random numbers. This is utilized in line 13, where Randomizer.Next(65, 91) produces a random number greater than or equal to 65 and less than 91. The Unicode numbers 65 and 90 represent the characters A and Z, respectively, with the rest of the alphabet in between (see Appendix E, "Unicode Character Set"). The randomly chosen number is cast to be of type char and turned into a string before it is assigned to secretLetter of type string. End result line 13 assigns a randomly chosen letter between A and Z to secretLetter.

The program is now ready to

  1. Assign the user input (the guess) to letterGuess (line 19).

  2. Compare letterGuess with secretLetter (lines 21 and 23).

  3. Provide an appropriate response to the user (lines 22 and 24).

  4. Determine if the loop should be terminated (line 26).

Because this sequence of actions must be repeated until the user enters the secret letter, an iteration statement is appropriate for implementing this functionality. The question then is should we use the while or the do-while construct? To answer this question, first have a look at the pseudocode in Figure 9.3. It summarizes the process described previously with an attempt to apply the while loop. Notice that the repeated part (the loop body) is repeated as long as secretLetter is not equal to letterGuess. However, the fact that letterGuess is utilized in the loop condition, but not assigned a value until the loop body is executed, poses a problem for our while loop and, in fact, renders the pseudocode incorrect.

Figure 9.3. Pseudocode of AlphabetGame applying while loop invalid solution.

If the while loop was the only available loop statement in C#, we could have worked around the problem and come up with a fully working, but inelegant program. Figure 9.4 presents the pseudocode behind such an attempt. By using the variable notGuessed of type bool with an initial value of true in the loop condition, we are able to execute the loop body at least once and obtain the first guess from the user. By making notGuessed false whenever the user guesses the secretLetter, the loop is terminated at the appropriate moment. In reality, then, line 9 has become our loop condition. Yes, it does work, and yes, it is pretty ugly and graceless.

Figure 9.4. Pseudocode of AlphabetGame applying while loop valid but ugly code.

Fortunately, the do-while loop, due to its exit condition, seamlessly supports the logic we want to represent in our AlphabetGame. The associated pseudocode is shown in Figure 9.5 and forms the basis for Listing 9.3.

Figure 9.5. Pseudocode of AlphabetGame applying do-while loop valid and elegant.

Line 3 of the pseudocode is implemented in line 19 of Listing 9.3. Notice that the letter is converted to uppercase, with the built-in ToUpper() method, allowing the user to input lower- and uppercase letters without making any difference. The comparisons between letterGuess and secretLetter along with appropriate feedback takes place in lines 21 24. Because secretLetter and letterGuess are of type System.String, we can utilize the built-in method CompareTo() presented in Chapter 4. The loop condition is located in line 25 and will cause the loop to terminate whenever secretLetter is equal to letterGuess.


C# Primer Plus
C Primer Plus (5th Edition)
ISBN: 0672326965
EAN: 2147483647
Year: 2000
Pages: 286
Authors: Stephen Prata

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: