Session Ready
Exercise

Breaking out of a for loop

Sometimes you may wish to exit a loop before you've completed all the iterations. For example, your code may succeed in its task before all possibilities have been tried. The break keyword can be used to break out of a loop early.

The code pattern looks like this:

for(int i = 0; i < n; i++) {
  // Do something

  // Test for exiting early
  if(breakout_condition) break;

  // Otherwise carry on as usual
}

Here you'll rework the previous example so that the loop stops when the value does not change too much (based on a threshold). The function has been modified so that it returns a List (you will learn about Lists in the next chapter), enabling you to see the approximation at each iteration.

This modified sqrt_approx() function returns both the square root and the number of iterations it took to achieve this result based on the threshold.

Instructions
100 XP

Add a break condition that triggers if the solution is good enough (based on the variable is_good_enough).