Break & Continue
in C++
Master the two key loop control statements that let you exit early or skip iterations for cleaner, more efficient code.
What Are Loop Control Statements?
Loops repeat code, but sometimes you need to change the normal flow inside a loop. C++ gives you two powerful keywords to do this:
Why Do We Need Them?
Without break and continue, you'd have to use complex boolean flags and deeply nested if statements to control loop behavior. These keywords make code:
Where They Work
Both break and continue can be used inside any of C++'s loop constructs:
How break Works
How continue Works
break vs continue: Key Distinction
| break | continue | |
|---|---|---|
| What it does | Exits the loop entirely | Skips to next iteration |
| Code after it | Never runs (in the loop) | Skipped for this iteration only |
| Remaining iterations | All cancelled | Continue as normal |
| Works in switch? | Yes | No |
| Common use | Search found, error detected | Skip invalid data, filter items |
The Rules to Remember
How to Apply Them
Example 1: break for Searching
Find the first negative number in an array and stop:
Example 2: continue for Filtering
Print only the even numbers from 1 to 10:
Example 3: Nested Loops
break only exits the innermost loop. Watch carefully:
Example 4: Danger in while Loops
Using continue in a while loop requires extra care:
while (i < 5) {
if (i == 3)
continue;
cout << i;
i++;
}
// Infinite loop at \(i = 3\)!
while (i < 4) {
i++;
if (i == 3)
continue;
cout << i << " ";
}
// Outputs: 0 1 2 4
Execution Trace: break vs continue
Looping \( i = 0 \) to \( 4 \), with the condition triggered at \( i = 2 \):
Common Mistakes
Summary Cheat Sheet
| Scenario | Use break? | Use continue? |
|---|---|---|
| Stop when a target is found | ✓ Yes | ✕ No |
| Skip invalid input values | ✕ No | ✓ Yes |
| Exit on error condition | ✓ Yes | ✕ No |
| Skip even/odd numbers | ✕ No | ✓ Yes |
| Process until a sentinel | ✓ Yes | ✕ No |
| Ignore blank lines in input | ✕ No | ✓ Yes |
Question 1 of 5
What does the break statement do when executed inside a loop?
Question 2 of 5
Code:
for (int i = 1; i <= 5; i++) {
if (i == 3) continue;
cout << i << " ";
}
What is the output of this code?
Question 3 of 5
Code:
int i = 0;
while (i < 5) {
if (i == 2) continue;
cout << i << " ";
i++;
}
What happens when this code runs?
Question 4 of 5
Code:
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (j == 1) break;
cout << i << j << " ";
}
}
What is the output?
Question 5 of 5
You are reading user input in a loop and want to skip blank lines but keep processing non-blank lines until the user types "quit". Which combination is correct?