Skip to content

Continue

The continue statement is used to jump back to the condition of the current loop. This can be very useful for skipping the processing of the current loop, while allowing the loop to continue for another cycle. See a visualisation of this in the image below.

The continue statement allows you to jump to the condition, skipping the remainder of the code in the loop but allowing the loop to continue

Continue — when, why, and how?

Like break, the continue statement isn’t something you use often. Most of the time you will want to execute the entire body of a loop. However, when needed you can use continue skip an iteration. This is typically done by using continue within a branching statement.

When you use continue in a for loop, the post-loop increment will still be executed to ensure that you move to the next value in the control variable. In a while loop, you need to make sure you have updated the condition before the continue statement so that you do not end up in an infinite loop.

In C

The continue statement is simply the continue keyword terminated by a semicolon (;).

How does continue work?

Skipping iterations in a for loop

The following code loops from 0 to 10, skipping all loops where i is larger than 0 and divisible by 3. Therefore, this will print 0, 1, 2, 4, 5, 7, 8, and 10 (skipping 3, 6, and 9).

using static System.Console;
using static System.Convert;
for (int i = 0; i < 11; i++)
{
if( i > 0 && i % 3 == 0)
{
continue;
}
WriteLine(i);
}

The following images show how this works.

Skipping iterations in a while loop

The following example is functionally the same as the previous, just using a while loop instead of a for loop. Note that this code also has an increment (i++) in the if statement. This makes sure that even when continue is executed the loop counter is incremented so that our code does not have an infinite loop. See if you can step through this code yourself and understand how it works the same way as the for loop above.

using static System.Console;
using static System.Convert;
int i = 0;
while (i < 11)
{
if ( i > 0 && i % 3 == 0 )
{
i++;
continue;
}
WriteLine(i);
i++;
}