C++ Break and Continue — Loop Control Guide | Tutorials Logic
break Statement
break immediately exits the innermost loop or switch statement. Execution continues with the statement after the loop.
#include <iostream>
using namespace std;
int main() {
// Find first number divisible by 7 between 1 and 50
for (int i = 1; i <= 50; i++) {
if (i % 7 == 0) {
cout << "First multiple of 7: " << i << endl; // 7
break; // exit loop immediately
}
}
// Linear search - stop when found
int arr[] = {5, 3, 8, 1, 9, 2};
int target = 8;
bool found = false;
for (int i = 0; i < 6; i++) {
if (arr[i] == target) {
cout << target << " found at index " << i << endl;
found = true;
break;
}
}
if (!found) cout << target << " not found" << endl;
// break only exits the INNERMOST loop
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (j == 1) break; // exits inner loop only
cout << "(" << i << "," << j << ") ";
}
}
cout << endl; // (0,0) (1,0) (2,0)
return 0;
}
continue Statement
continue skips the rest of the current iteration and jumps to the next one. The loop itself does not exit.
#include <iostream>
using namespace std;
int main() {
// Print only odd numbers 1"10
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) continue; // skip even numbers
cout << i << " ";
}
cout << endl; // 1 3 5 7 9
// Skip negative numbers when summing
int nums[] = {5, -3, 8, -1, 4, -7, 2};
int sum = 0;
for (int n : nums) {
if (n < 0) continue; // skip negatives
sum += n;
}
cout << "Sum of positives: " << sum << endl; // 19
// Print numbers 1"20, skip multiples of 3 and 5
for (int i = 1; i <= 20; i++) {
if (i % 3 == 0 || i % 5 == 0) continue;
cout << i << " ";
}
cout << endl; // 1 2 4 7 8 11 13 14 16 17 19
return 0;
}
Key Takeaways
- break exits the innermost loop or switch statement immediately.
- continue skips the rest of the current iteration and moves to the next one.
- In nested loops, break and continue only affect the innermost loop.
- Use a flag variable or goto (sparingly) to break out of multiple nested loops.
- break in a switch statement prevents fall-through to the next case.
- Overusing break and continue can make code harder to follow - consider refactoring into functions.
Level Up Your C plus plus Skills
Master C plus plus with these hand-picked resources
10,000+ learners
Free forever
Updated 2026
Related C++ Topics