The continue statement: skipping to the next iteration
What you'll learn: How to use the continue keyword to bypass the remaining code in a loop and jump immediately to the next cycle.
Skipping the line
In the previous lesson, we saw how break kills a loop entirely. The continue statement is a bit more polite: it doesn't stop the loop, it just skips the rest of the current turn.
Imagine you are a teacher grading a stack of 30 exams. You pick up a paper, check the name, and realize the student was absent and left it blank. You don't throw away the whole stack of 30 papers and go home (that would be a break). Instead, you simply set that one blank paper aside and move straight to the next one in the pile. You "continued" to the next iteration.
How it works in code
When a program hits a continue statement, it ignores every line of code sitting below it inside that loop’s curly braces. It then jumps back to the top of the loop to check the condition again (or increment the counter) and starts the next round.
This is incredibly useful for filtering out "bad data" or specific cases you don't want to process.
#include <stdio.h>
int main() {
// Let's print numbers 1 to 5, but skip 3
for (int i = 1; i <= 5; i++) {
if (i == 3) {
// When i is 3, we jump back to the top
// and increment i to 4.
continue;
}
printf("Number: %d\n", i);
}
return 0;
}
In the example above, when i equals 3, the printf function is never called. The loop sees continue and immediately rushes back to the top to turn that 3 into a 4.
Why use it?
You use continue to keep your code clean. Without it, you often end up with deeply nested if statements. By using continue to handle "exceptions" early, the rest of your loop logic can sit plainly at the bottom, knowing that any invalid data has already been skipped. It’s like a filter that keeps the "junk" from reaching the main part of your logic.
Key takeaway
The continue statement ends the current iteration early and jumps straight to the start of the next one.