The while Loop Statement

   


The while Loop Statement

The while loop repeats a statement or compound statement again and again, here referred to as loop body, as long as its associate loop condition, consisting of a Boolean expression, is true (see Syntax Box 9.1). When the loop condition is false while being evaluated, flow of control moves to the line immediately following the while loop.

Syntax Box 9.1 The while-Loop

 while_statement:= while (<Loop_condition>)     <Loop_body> 

where:

 <Loop_condition>::= <Boolean_expression> <Loop_body>::= <Statement>;            ::= <Compound_statement> 

Note:

  • The loop body is repeated as long as <Loop_condition> is true.

The keyword while is suitably chosen; we can even use it to describe the semantics of the while loop in plain English:

While (the loop condition is true) repeat the loop body over and over again.

Note

graphics/common.gif

One of the best ways to learn the inner logic of the various loop constructs presented here is to trace the examples given, just as you have traced the pseudocode and source code presented in earlier chapters. In particular, try to focus on the variable(s) involved in the loop condition of the iteration. Look at its (their) initial values and the positions where it (they) is altered; this will provide you with the key information needed to determine how many times the loop will repeat itself.


Listing 9.1 presents a simple example utilizing the while loop to print out the numbers from 0 to 4.

Listing 9.1 A while loop Incomplete Source Code
01: int index; 02: index = 0; 03: while (index < 5) 04: { 05:     Console.WriteLine(index); 06:     index++; 07: } 0 1 2 3 4 

The while statement begins with the keyword while in line 3 and is followed by its associated loop condition index < 5 enclosed by parentheses. The loop body in lines 5 and 6 is enclosed by a matching pair of braces in lines 4 and 7 and constitute a compound statement that is executed repeatedly.

index is part of the loop condition in line 3 and acts as a loop termination controller. Thus, to facilitate our analysis, we need to focus on the source code locations that change the value of index. The hotspots are as follows:

  • Initialization of index to 0 in line 2 (called loop initialization)

  • Incrementing index by 1 in line 6 (called loop update)

As long as index < 5 is true, the loop body is repeated. Because index, due to its initialization of line 2, has the value 0, when line 3 is executed for the first time, index < 5 is true and the loop body executed. Thus, line 5 prints out a 0 (see sample output) and line 6 increments index by 1 to hold the value 1. Flow of control then returns to line 3. Because index is 1, (index < 5) is still true, causing another printout and increment of index.

Notice that every time the loop body is repeated, index is nearing the point where index < 5 becomes false due to line 6. After four repetitions, index is equal to 4 and index < 5 is still true causing 4 to be printed out in line 5 and index to be incremented to 5 in line 6. The flow of control once again jumps back to line 3 where index < 5 this time is false, prompting the loop to terminate and move to the next statement after the while loop, which in this case would be line 8.

Verify that the Loop Eventually Terminates

graphics/bulb.gif

The analysis of Listing 9.1 convinced us that every repeated execution of the loop body gradually carried the loop variable closer to terminating the loop. In general, it is recommended that you mentally trace the execution of a loop to ensure that, under any set of circumstances, it will terminate.


A loop construct, such as the while loop, that contains its loop condition at the beginning of the loop is called an entry-condition loop.

Note

graphics/common.gif

The loop condition of any of the iteration statements in C# is only evaluated once during each repeated execution of the loop body.



graphics/09infig01.gif

The Boolean expression is tested at the beginning of the while loop; thus, if the Boolean expression is false initially, the loop body is never executed. This is an essential feature as demonstrated in Listing 9.2. The program presented in Listing 9.2 lets the user choose, by inputting an integer value, the number of times a piece of music should be played again. Each piece of music being played is simply symbolized by printing Play onscreen. When the user enters a 0, the while loop never executes its loop body, appropriately preventing Play from being written onscreen even once.

Listing 9.2 PlayItAgain.cs
01: using System; 02: 03: class PlayItAgain 04: { 05:     public static void Main() 06:     { 07:         int counter; 08:         Console.WriteLine("Play"); 09:         Console.Write("Sam says: Play it again how many times? "); 10:         counter = Convert.ToInt32(Console.ReadLine()); 11:         while(counter > 0) 12:         { 13:             Console.WriteLine("Play"); 14:             counter--; 15:         } 16:         Console.WriteLine("That's it folks!"); 17:     } 18: } 

Sample output 1:

 Play Sam: Play it again how many times? 3<enter> Play Play Play That's it folks! 

Sample output 2:

 Play Sam: Play it again how many times? 0<enter> That's it folks! 

counter plays the same pivotal role for the while statement here as index does for the while statement in Listing 9.1, but with a few notable adjustments. Instead of starting at zero like index, counter begins at the number provided by the end user, which ultimately is the number of times the word Play will be displayed onscreen. To accommodate for this modification and still allow the while loop to function correctly, the comparison operator of the Boolean expression in line 11 has been reversed from less-than (in line 3 of Listing 9.1) to greater-than, and instead of incrementing it by 1, counter is now being decremented by 1 in line 14. Through these adjustments, we can utilize the number entered by the end user as is and, at the same time, preserve the overall logic found in Listing 9.1 every time the loop statements are repeated, counter moves closer towards making (counter > 0) false. In this case, it takes counter (its initial value) repetitions to make counter > 0 equal to false.

Tip

graphics/bulb.gif

Always position the loop initializations immediately before the loop.

The previous two examples, demonstrating the use of the while statement, positioned the initialization statements immediately before the while loop. This is not a coincidence but represents an important rule of thumb loop initializations should always be positioned immediately before the loop. Not only does this allow the reader easy access to this important code while looking at the loop, it further stands as a reminder to include the loop initialization in any modifications made to the loop itself.


The majority of computational problems requiring a loop construct as part of its solution call for a loop statement with the exit point at the beginning, such as the while loop, to be implemented correctly and elegantly. However, in certain contexts, a loop construct with the exit point after the loop body can provide for a more elegant solution. The do-while loop presented in the next section provides this type of functionality.


   


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

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net