Break Statement
Now we'll look at the break
statement, which allows us to terminate a loop early. Imagine you want to buy a house, so you go look at houses for sale every day. But once you buy a house, you don't want to look at houses anymore because you already have one. The break
statement allows you to do this. The break
statement terminates the current loop.
For example, we want to find the first even number between 1
and 10
:
int number = 1;
while (number <= 10) {
if (number % 2 == 0) { // If the number is even
std::cout << number << std::endl;
break; // Terminate the loop
}
number++;
}
Prints:
2
In this example, we go through numbers from 1
to 10
. As soon as we encounter the first even number, we print it and terminate the loop using break
.
Without break
, the loop would continue and print all even numbers in the sequence.
To explain the condition number % 2 == 0: the % operation returns the remainder after division, and when the remainder after dividing number
by two equals 0, it means number
is even.
Instructions
Create a variable count
of type int with initial value 1.
Using a while
loop, go through count
from 1 to 10 and print count
when it's greater than 5 and terminate the loop. Use the break
statement for this.
Don't forget to increment the variable count
by 1.
Start programming for free
5/9