-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbreak-continue.cpp
More file actions
65 lines (52 loc) · 1.75 KB
/
Copy pathbreak-continue.cpp
File metadata and controls
65 lines (52 loc) · 1.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include <iostream>
using namespace std;
int main() {
// ===================================================
// 1. BREAK IN FOR LOOP
// ===================================================
// 'break' completely exits the loop immediately
cout << "=== 1. BREAK IN FOR LOOP ===" << endl;
for (int i = 0; i < 10; i++) {
if (i == 4) {
break; // Jumps out of the loop when i reaches 4 (prints 0 to 3)
}
cout << i << "\n";
}
// ===================================================
// 2. CONTINUE IN FOR LOOP
// ===================================================
// 'continue' skips the rest of current iteration and moves to the next
cout << "\n=== 2. CONTINUE IN FOR LOOP ===" << endl;
for (int i = 0; i < 10; i++) {
if (i == 4) {
continue; // Skips printing 4, then continues loop from 5
}
cout << i << "\n";
}
// ===================================================
// 3. BREAK IN WHILE LOOP
// ===================================================
cout << "\n=== 3. BREAK IN WHILE LOOP ===" << endl;
int j = 0;
while (j < 10) {
cout << j << "\n";
j++;
if (j == 4) {
break; // Stops and exits the while loop when j hits 4
}
}
// ===================================================
// 4. CONTINUE IN WHILE LOOP
// ===================================================
cout << "\n=== 4. CONTINUE IN WHILE LOOP ===" << endl;
int k = 0;
while (k < 10) {
if (k == 4) {
k++; // Crucial: increment before continue to avoid an infinite loop!
continue; // Skips printing 4
}
cout << k << "\n";
k++;
}
return 0;
}