Break
Part of the Fundamentals section of Coddy's C++ journey — lesson 45 of 74.
The break statement stops the loop instantly when it's encountered.
For example,
for (int i = 0; i < 10; i++) {
if (i == 6) {
break;
}
std::cout << i << std::endl;
}In the following example the loop iterates regularly until it reaches number 6. Then the program enters the if statement and executes the break statement. This exits the loop immediately. The output is:
0
1
2
3
4
5Challenge
BeginnerYou are given a code that prints the numbers from 1 to 20 (including).
Your task is to add if and break statements so that only the numbers from 1 to 15 will be printed, the loop will exit before printing the numbers from 16 to 20.
Cheat sheet
The break statement stops the loop instantly when it's encountered.
for (int i = 0; i < 10; i++) {
if (i == 6) {
break;
}
std::cout << i << std::endl;
}This loop exits when i equals 6, printing numbers 0 through 5.
Try it yourself
#include <iostream>
int main() {
for (int i = 1; i <= 20; i++) {
std::cout << i << std::endl;
}
return 0;
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorIncrement/DecrementPost Increment/DecrementArithmetic ShortcutsComparison OperatorsString Comparison3Variables Part 2
Type DeclarationNaming ConventionsRecap - Initialize VariablesType Casting Part 1Type Casting Part 26Decision Making
If StatementIf - ElseSwitch StatementConditional OperatorRecap - If ElseNested If - Else