The while Loop


Another of C#’s loops is the while. The general form of the while loop is

 while(condition) statement;

where statement can be a single statement or a block of statements, and condition defines the condition that controls the loop, and it may be any valid Boolean expression. The statement is performed while the condition is true. When the condition becomes false, program control passes to the line immediately following the loop.

Here is a simple example in which a while is used to compute the order of magnitude of an integer:

 // Compute the order of magnitude of an integer using System; class WhileDemo {   public static void Main() {     int num;     int mag;     num = 435679;     mag = 0;     Console.WriteLine("Number: " + num);     while(num > 0) {       mag++;       num = num / 10;     };     Console.WriteLine("Magnitude: " + mag);   } }

The output is shown here:

 Number: 435679 Magnitude: 6

The while loop works like this: The value of num is tested. If num is greater than zero, the mag counter is incremented, and num is divided by 10. As long as the value in num is greater than zero, the loop repeats. When num is zero, the loop terminates and mag contains the order of magnitude of the original value.

As with the for loop, the while checks the conditional expression at the top of the loop, which means that the loop code may not execute at all. This eliminates the need for performing a separate test before the loop. The following program illustrates this characteristic of the while loop. It computes the integer powers of 2 from 0 to 9.

 // Compute integer powers of 2. using System; class Power {   public static void Main() {     int e;     int result;     for(int i=0; i < 10; i++) {       result = 1;       e = i;       while(e > 0) {         result *= 2;         e--;       }       Console.WriteLine("2 to the " + i +                          " power is " + result);     }   } }

The output from the program is shown here:

 2 to the 0 power is 1 2 to the 1 power is 2 2 to the 2 power is 4 2 to the 3 power is 8 2 to the 4 power is 16 2 to the 5 power is 32 2 to the 6 power is 64 2 to the 7 power is 128 2 to the 8 power is 256 2 to the 9 power is 512

Notice that the while loop executes only when e is greater than zero. Thus, when e is zero, as it is in the first iteration of the for loop, the while loop is skipped.




C# 2.0(c) The Complete Reference
C# 2.0: The Complete Reference (Complete Reference Series)
ISBN: 0072262095
EAN: 2147483647
Year: 2006
Pages: 300

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