Lesson 4
Repeated Practice Makes Perfect
Chapter 5: Breaking the flow
break
You may have previously struggled a bit with trying to elegantly exit a loop, especially when you have fulfilled some criteria early on.
For example, below is my implementation of the exhaustive search algorithm for square root from earlier. Do you find it hard to read and to understand?
1 2 3 4 5 6 7 8 9 |
|
Compare the code above to the one below. The break
statement (Line 6) will force your program to exit the nearest loop. In this case, it will bring your program straight to Line 10. Do you feel that it is easier to read than the above?
1 2 3 4 5 6 7 8 9 10 |
|
The break
statement allows you to make a ‘quick exit’ from a loop. You will tend to use it with an if
statement. When your program interpreter hits a break
statement, it will forcefully ‘break out’ from the nearest loop you are currently in.