The continue Statement

The continue statement is the smaller sibling of break. It doesn't end the whole loop, only the current iteration: it skips the rest of the block, and the loop goes straight on to the next iteration.

This loop prints the numbers from 1 to 10, but skips the multiples of 3:

for (int number = 1; number <= 10; number++) {
    if (number % 3 == 0) {
        continue;
    }
    printf("%d\n", number);
}

This prints:

1
2
4
5
7
8
10

For 3, 6 and 9, the condition is true, and continue skips the line that prints. The step number++ still runs, and the loop carries on with the next number as usual.

The continue statement usually sits at the beginning of the block and filters out the values you don't want to deal with: “this one doesn't interest me, on to the next one”. The rest of the block then only handles the interesting ones, and you don't have to put all of it inside an if.

Be careful with continue in a while loop. It jumps straight back to the condition, so if the line that increases the counter is below continue, it is skipped too. The counter stops changing, and you get an infinite loop. In a for loop, this can't happen: its step runs after every iteration, including one that ended with continue.

Instructions

The loop prints the first 14 days of a month that starts on a Monday, but you only want the working days. At the start of the loop's block, write an if that skips the day with continue when it is a Saturday or a Sunday. Saturdays are the days where day % 7 == 6, Sundays the days where day % 7 == 0. The program then prints Day 1 to Day 5 and Day 8 to Day 12.

Count the working days. Before the loop, create a variable working_days with the value 0. In the loop, below the if with continue, increase it by 1. After the loop, print Working days: 10.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

8/11