capypad
0 day streak
cpp / beginner
Snippet

Break and Continue: Controlling Loop Execution

The break statement immediately exits the nearest enclosing loop, skipping all remaining iterations. The continue statement skips the rest of the current iteration and jumps to the next iteration. In this example, when i is 3, continue skips printing that number. When i reaches 8, break exits the loop entirely, so numbers 8, 9, and 10 are never printed.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
using namespace std;
 
int main() {
for (int i = 1; i <= 10; i++) {
if (i == 3) {
continue;
}
if (i == 8) {
break;
}
cout << "Number: " << i << endl;
}
return 0;
}
Breakdown
1
if (i == 3) { continue; }
When i equals 3, skip the rest of this iteration - cout below is bypassed
2
if (i == 8) { break; }
When i equals 8, exit the loop completely - program continues after the for loop
3
cout << "Number: " << i << endl;
Only executes for i values of 1,2,4,5,6,7 (3 skipped by continue, 8+ never reached due to break)
4
Output: 1, 2, 4, 5, 6, 7
Numbers 3 and 8+ are not printed due to continue and break logic