Information Technology Reference
In-Depth Information
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.
￿Firs , TestExpr is evaluated.
￿ f 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");
The output from this code is the following:
x: 3
x: 2
x: 1
Out of loop
Search WWH ::




Custom Search