Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Daniel Solis - Illustrated C# 2010 - 2010.pdf
Скачиваний:
16
Добавлен:
11.06.2015
Размер:
11.23 Mб
Скачать

CHAPTER 9 STATEMENTS

The while Loop

The while loop is a simple loop construct in which the test expression is performed at the top of the loop. The syntax of the while loop is shown here and is illustrated in Figure 9-6.

First, TestExpr is evaluated.

If TestExpr evaluates to false, then execution continues after the end of the while loop.

Otherwise, when TestExpr evaluates to true, then Statement is executed, and TestExpr is evaluated again. Each time TestExpr evaluates to true, Statement is executed another time. The loop ends when TestExpr evaluates to false.

while( TestExpr ) Statement

Figure 9-6. The while loop

The following code shows an example of the while loop, where the test expression variable starts with a value of 3 and is decremented at each iteration. The loop exits when the value of the variable becomes 0.

int x = 3; while( x > 0 )

{

Console.WriteLine("x: {0}", x); x--;

}

Console.WriteLine("Out of loop");

This code produces the following output:

x:3

x:2

x:1

Out of loop

250

CHAPTER 9 STATEMENTS

The do Loop

The do loop is a simple loop construct in which the test expression is performed at the bottom of the loop. The syntax for the do loop is shown here and illustrated in Figure 9-7.

First, Statement is executed.

Then, TestExpr is evaluated.

If TestExpr returns true, then Statement is executed again.

Each time TestExpr returns true, Statement is executed again.

When TestExpr returns false, control passes to the statement following the end of the loop construct.

do

 

Statement

 

while( TestExpr );

// End of do loop

Figure 9-7. The do loop

251

CHAPTER 9 STATEMENTS

The do loop has several characteristics that set it apart from other flow-of-control constructs. They are the following:

The body of the loop, Statement, is always executed at least once, even if TestExpr is initially false.

The semicolon is required after the closing parenthesis of the test expression.

The following code shows an example of a do loop:

int x = 0; do

Console.WriteLine("x is {0}", x++);

while (x<3);

Required

This code produces the following output:

x is 0 x is 1 x is 2

252

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]