Break and Continue
Loop control statements
Interview Relevant: Flow control in loops
Break and Continue
Control statements that alter loop execution flow.
Behavior
- break: Exit the loop entirely
- continue: Skip to the next iteration
Code Examples
Using break and continue for loop control.
cpp
1// break - exit loop early
2for (int i = 0; i < 10; i++) {
3 if (i == 5) break;
4 cout << i << " "; // 0 1 2 3 4
5}
6
7// continue - skip current iteration
8for (int i = 0; i < 10; i++) {
9 if (i % 2 == 0) continue; // Skip even numbers
10 cout << i << " "; // 1 3 5 7 9
11}
12
13// break in nested loops (only breaks inner loop)
14for (int i = 0; i < 3; i++) {
15 for (int j = 0; j < 3; j++) {
16 if (j == 1) break;
17 cout << i << "," << j << " ";
18 }
19}
20// Output: 0,0 1,0 2,0
21
22// Finding first match
23vector<int> nums = {1, 3, 5, 7, 8, 9};
24for (int n : nums) {
25 if (n % 2 == 0) {
26 cout << "First even: " << n << endl;
27 break;
28 }
29}