break immediately exits the nearest enclosing loop or switch.
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 10; i++) {
if (i == 5) break; // stop when i reaches 5
cout << i << " ";
}
cout << endl;
return 0;
}
Output:
1 2 3 4
continue Statement
continue skips the rest of the current iteration and jumps to the next one.
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) continue; // skip even numbers
cout << i << " ";
}
Output:
1 3 5 7 9
break in Nested Loops
break only exits the innermost loop it is inside:
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
if (j == 2) break; // exits inner loop only
cout << i << "," << j << " ";
}
cout << endl;
}
Output:
1,1
2,1
3,1
Exercise
Use a while loop and break to keep asking the user for a number until they enter 0. Print each number entered.
Show Solution
#include <iostream>
using namespace std;
int main() {
int n;
while (true) {
cout << "Enter a number (0 to quit): ";
cin >> n;
if (n == 0) break;
cout << "You entered: " << n << endl;
}
cout << "Goodbye!" << endl;
return 0;
}
Quiz
What does continue do in a loop?
A) Exits the loop
B) Restarts the program
C) Skips the current iteration and goes to the next
D) Pauses execution
Answer
C)continue skips the remaining code in the current iteration and begins the next one.
If you have nested loops and use break, which loop exits?
A) The outermost loop
B) All loops
C) The innermost loop
D) The loop with the break label
Answer
C)break exits only the innermost enclosing loop.
Summary
break exits the current loop or switch immediately.
continue skips the rest of the current iteration.
In nested loops, break only exits the innermost loop.