The do-while Loop


The third C# loop is the do-while. Unlike the for and the while loops, in which the condition is tested at the top of the loop, the do-while loop checks its condition at the bottom of the loop. This means that a do-while loop will always execute at least once. The general form of the do-while loop is

 do {    statements; } while(condition);

Although the braces are not necessary when only one statement is present, they are often used to improve readability of the do-while construct, thus preventing confusion with the while. The do-while loop executes as long as the conditional expression is true.

The following program uses a do-while loop to display the digits of an integer in reverse order:

 // Display the digits of an integer in reverse order. using System; class DoWhileDemo {   public static void Main() {     int num;     int nextdigit;     num = 198;     Console.WriteLine("Number: " + num);     Console.Write("Number in reverse order: ");     do {       nextdigit = num % 10;       Console.Write(nextdigit);       num = num / 10;     } while(num > 0);     Console.WriteLine();   } }

The output is shown here:

 Number: 198 Number in reverse order: 891

Here is how the loop works. With each iteration, the leftmost digit is obtained by calculating the remainder of an integer division by 10. This digit is then displayed. Next, the value in num is divided by 10. Since this is an integer division, this results in the leftmost digit being removed. This process repeats until num is zero.




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