Curriculum
In C#, the continue
keyword is used to skip the current iteration of a loop and move on to the next iteration.
Here’s an example of using the continue
keyword inside a for
loop:
for (int i = 0; i < 10; i++) { if (i == 5) { continue; } Console.WriteLine(i); }
In this example, the for
loop will iterate from i=0
to i=9
. However, when i=5
, the continue
statement is executed, and the current iteration of the loop is skipped. Therefore, only the values of i
from 0
to 4
and 6
to 9
will be printed to the console.
The continue
keyword can also be used inside a while
or do-while
loop, as shown in the following example:
int i = 0; while (i < 10) { i++; if (i % 2 == 0) { continue; } Console.WriteLine(i); }
In this example, the while
loop will iterate from i=1
to i=10
. However, when i
is even (i.e., i % 2 == 0
), the continue
statement is executed, and the current iteration of the loop is skipped. Therefore, only the odd values of i
from 1
to 9
will be printed to the console.
The rules for using the continue
keyword in C# are as follows:
continue
statement can only be used inside a loop.continue
statement is executed inside a loop, the current iteration of the loop is skipped, and the control flow moves to the next iteration.continue
statement is executed inside a nested loop, only the innermost loop is affected, and the outer loops continue to iterate normally.In summary, the continue
keyword is a useful tool for controlling the flow of execution in C# loops. By using the continue
keyword, you can skip certain iterations of a loop and focus on the iterations that are relevant to your program.