Section 4.4 Breaking out of a loop
In Section 4.2 we noted an issue with while
loop: it can go on forever, or for such a long time that we simply have to give up on the computation and maybe try something else. The command break
exits the loop (it can be either for
or while
loop). This command is always contained in an if
statement because the idea is to break out of the loop when some condition is reached. Here is an example of such situation. Starting with x=1
, the code repeatedly replaces x with \(\frac{1}{2}(x + a/x)\) where the number a
is provided by the user.
a = input('a = '); tries = 1000; x = 1; for k = 1:tries newx = (x + a/x)/2; if abs(newx - x) < 1e-9 break end x = newx; end if k < tries fprintf('Converged to x = %.9f\n', newx) else disp('Failed to converge') end
The loop has a limit of 1000 tries. It ends sooner if the required condition “new x is close to old one” is reached. After the loop there is another conditional statement which reports the result depending on whether the loop terminated early (success) or ran out of tries (failure). Try running this script with different inputs such as 2, -3, 4, -5, 6. What do you observe?