cpp / beginner
Snippet
Break and Continue: Controlling Loop Flow
The break statement immediately exits the innermost loop, stopping all further iterations. The continue statement skips the rest of the current iteration and jumps to the next iteration. In this example, when i equals 3, continue skips printing and moves to the next i value. When i equals 7, break exits the loop entirely. The output shows values 0, 1, 2, 4, 5, 6 before the loop ends at 7.
snippet.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>int main() {for (int i = 0; i < 10; i++) {if (i == 3) {continue;}if (i == 7) {break;}std::cout << "i = " << i << std::endl;}std::cout << "Loop ended" << 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) {
Check if current i equals 3
3
continue;
Skip to next iteration, skipping the cout line
4
}
End of if block
5
if (i == 7) {
Check if current i equals 7
6
break;
Exit the loop completely
7
}
End of if block
8
std::cout << "i = " << i << std::endl;
Print i for values not skipped or stopped
9
}
End of for loop body
10
std::cout << "Loop ended" << std::endl;
Printed after break exits the loop