In C++, the break
and continue
statements allow for better control of loops, enabling you to exit loops early or skip specific iterations.
Break Statement
The break
statement immediately stops a loop when a specified condition is met, preventing further execution of remaining iterations.
Example: Exiting a Loop When a Condition Is Met
C++
x
using namespace std;
int main() {
for (int speed = 0; speed < 10; speed++) {
if (speed == 4) {
break; // Stops the loop when speed reaches 4
}
cout << "Current speed level: " << speed << "\n";
}
return 0;
}
Output:
C++
Current speed level: 0
Current speed level: 1
Current speed level: 2
Current speed level: 3
The loop stops once speed reaches 4, preventing further execution.
Continue Statement
The continue
statement skips the current iteration when a condition is met and proceeds to the next loop iteration.
Example: Skipping a Specific Value
C++
using namespace std;
int main() {
for (int gear = 0; gear < 10; gear++) {
if (gear == 4) {
continue; // Skips gear 4 and moves to the next
}
cout << "Current gear: " << gear << "\n";
}
return 0;
}
Output:
C++
Current gear: 0
Current gear: 1
Current gear: 2
Current gear: 3
Current gear: 5
Current gear: 6
Current gear: 7
Current gear: 8
Current gear: 9
Notice that gear 4 is missing, as it was skipped.
Using Break and Continue in While Loops
Example: Breaking Out of a while Loop
C++
using namespace std;
int main() {
int rpm = 0;
while (rpm < 10) {
cout << "RPM Level: " << rpm << "\n";
rpm++;
if (rpm == 4) {
break; // Stops loop when RPM reaches 4
}
}
return 0;
}
Example: Using continue in a while Loop
C++
using namespace std;
int main() {
int speed = 0;
while (speed < 10) {
if (speed == 4) {
speed++;
continue; // Skips speed level 4
}
cout << "Speed setting: " << speed << "\n";
speed++;
}
return 0;
}