The break Statement
Sometimes you don't need to go through the whole loop. When you are looking for something and you find it, there is no reason to keep looking. The break statement ends the loop immediately, and the program continues with the code after the loop. You already know break from switch, where it ends the switch. In a loop, it ends the loop.
Let's find the first number from 100 up that is divisible by 7. The loop prints each number it checks, so that you can see where it stops:
for (int number = 100; number < 200; number++) {
printf("Checking %d\n", number);
if (number % 7 == 0) {
printf("First multiple of 7: %d\n", number);
break;
}
}
printf("Done\n");Checking 100
Checking 101
Checking 102
Checking 103
Checking 104
Checking 105
First multiple of 7: 105
DoneThe condition number % 7 == 0 is true when the remainder after dividing by 7 is 0. When the loop gets to 105, the condition is true. The program prints the result, and break ends the loop: the numbers from 106 on are never checked, and the program goes on with the line that prints Done. Without break, the loop would run all the way to 199 and print all 14 multiples of 7, not just the first one.
You will almost always put break inside an if. On its own, it would end the loop during its very first iteration. break works the same way in while and for loops.
Often you also need to know after the loop what you found. Then store it in a variable created before the loop. Which is the smallest whole number whose square is greater than 500?
int found = 0;
for (int n = 1; n <= 100; n++) {
if (n * n > 500) {
found = n;
break;
}
}
printf("Smallest: %d\n", found);
printf("Its square: %d\n", found * found);Smallest: 23
Its square: 52922 * 22 is 484, which isn't enough, but 23 * 23 is 529. Thanks to break, found keeps the first number that is big enough. Without break, the loop would go on, store every larger number too, and found would end up as 100.
Instructions
In a game, you have 200 coins and earn 50 more every day. You are saving for a sword that costs 590 coins. The loop in the editor prints how many coins you have on each of the next 14 days. In the loop, below the line that prints the coins, add an if that prints Day 8: you can buy the sword! (with the day's number) when you have at least 590 coins. Run the program: the message appears on every day from day 8 on, but you only want to know the first day.
Add break to the block of the if, after the printing, so that the loop stops on the first day you can buy the sword. Now the output ends with Day 8: 600 coins and Day 8: you can buy the sword!.
Start programming for free
7/11