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
10For 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
- 1
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
ifthat skips the day withcontinuewhen it is a Saturday or a Sunday. Saturdays are the days whereday % 7 == 6, Sundays the days whereday % 7 == 0. The program then printsDay 1toDay 5andDay 8toDay 12. - 2
Count the working days. Before the loop, create a variable
working_dayswith the value0. In the loop, below theifwithcontinue, increase it by 1. After the loop, printWorking days: 10.