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;
}
std::cout << number << std::endl;
}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 elements 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.
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 the loop gets stuck. In a for loop, this can't happen: its step runs after every iteration, including one that ended with continue, and the range-based for moves on to the next element by itself.
Instructions
- 1
Your phone counts your steps every day. The vector
dailyStepsholds the counts for six days, and-1means the phone was switched off that day. Write aforloop overdailySteps. At the start of its block, write anifthat skips the value withcontinuewhen it is-1. - 2
After the
if, still inside the loop, print the value. The output is4200,6100,3800and7500, each on its own line. - 3
Now work out the average number of steps on the days that were measured. Before the loop, create the variables
totalanddays, both with the value0. In the loop, below theifwithcontinue, add the value tototaland increasedaysby 1. After the loop, printtotal / daysasAverage: 5400. Divide bydays, not by the size of the vector: the skipped days don't count.