capypad
0 day streak
cpp / beginner
Snippet

Break and Continue in Loops

The break statement immediately exits the innermost loop, while continue skips the rest of the current iteration and moves to the next one. In this example, when i equals 3, continue skips printing for that number. When i equals 7, break exits the loop entirely. These statements provide fine-grained control over loop execution.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
 
int main() {
for (int i = 0; i < 10; i++) {
if (i == 3) {
continue;
}
if (i == 7) {
break;
}
std::cout << "Number: " << i << std::endl;
}
std::cout << "Loop stopped at i = 7" << std::endl;
return 0;
}
Breakdown
1
for (int i = 0; i < 10; i++) {
For loop iterating i from 0 to 9
2
if (i == 3) {
Checks if current number is 3
3
continue;
Skips remaining code in this iteration, jumps to next i
4
}
Closes the if statement
5
if (i == 7) {
Checks if current number is 7
6
break;
Exits the for loop completely
7
}
Closes the if statement
8
std::cout << "Number: " << i << std::endl;
Prints number if neither condition triggered
9
}
Closes the for loop body
10
std::cout << "Loop stopped at i = 7" << std::endl;
Prints final message after loop exits via break