Information Technology Reference
In-Depth Information
The continue Statement
The
continue
statement causes program execution to go to the
top
of the
innermost enclosing
loop
of the following types:
while
do
for
foreach
For example, the following
for
loop is executed five times. In the first three iterations, it
encounters the
continue
statement and goes directly back to the top of the loop, missing the
WriteLine
statement at the bottom of the loop. Execution only reaches the
WriteLine
state-
ment during the last two iterations.
for( int x=0; x<5; x++ ) // Execute loop five times
{
if( x < 3 ) // The first three times
continue; // Go directly back to the top of loop.
// This line is only reached when x is 3 or greater.
Console.WriteLine("Value of x is {0}", x);
}
The output of this code is the following:
Value of x is 3
Value of x is 4
The following code shows an example of a
continue
statement in a
while
loop. This code
has the same output as the preceding
for
loop example.
int x = 0;
while( x < 5 )
{
if( x < 3 )
{
x++;
continue; // Go back to top of loop
}
// This line is reached only when x is 3 or greater.
Console.WriteLine("Value of x is {0}", x);
x++;
}