PART I
C h a p t e r 5 :
P r o g r a m C o n t r o l S t a t e m e n t s
105
PART IPART I
// Use continue.
using System;
class ContDemo {
static void Main() {
// Print even numbers between 0 and 100.
for(int i = 0; i <= 100; i++) {
if((i%2) != 0) continue; // iterate
Console.WriteLine(i);
}
}
}
Only even numbers are printed, because an odd number will cause the loop to iterate early,
bypassing the call to
WriteLine( )
.
In
while
and
do-while
loops, a
continue
statement will cause control to go directly to
the conditional expression and then continue the looping process. In the case of the
for
, the
iteration expression of the loop is evaluated, then the conditional expression is executed,
and then the loop continues.
Good uses of
continue
are rare. One reason is that C# provides a rich set of loop statements
that fit most applications. However, for those special circumstances in which early iteration
is needed, the
continue
statement provides a structured way to accomplish it.
Do'stlaringiz bilan baham: |