while Loops, break & continue
A while loop repeats as long as a condition is true. Use it when you don't know in advance how many iterations you'll need: iterate until a value converges, until a balance reaches a target, until the input runs out.
balance = 1000;
years = 0;
while balance < 2000
balance = balance * 1.06;
years = years + 1;
end
fprintf('After %d years the balance is %.2f\n', years, balance);After 12 years the balance is 2012.20
The condition is checked before each pass. If it is false at the start, the body never runs. Something inside the loop must eventually make the condition false, otherwise the loop runs forever (press Ctrl+C to stop it).
Iterating until convergence
A classic numerical use: Newton's method for √a repeats x = (x + a/x) / 2 until two successive estimates agree within a tolerance:
a = 10;
x = a; % first guess
step = Inf;
iterations = 0;
while abs(step) > 1e-10
newX = (x + a / x) / 2;
step = newX - x;
x = newX;
iterations = iterations + 1;
fprintf('iteration %d: %.10f\n', iterations, x);
end
fprintf('sqrt(%d) = %.10f (built-in: %.10f)\n', a, x, sqrt(a));iteration 1: 5.5000000000
iteration 2: 3.6590909091
iteration 3: 3.1960050819
iteration 4: 3.1624556228
iteration 5: 3.1622776652
iteration 6: 3.1622776602
iteration 7: 3.1622776602
sqrt(10) = 3.1622776602 (built-in: 3.1622776602)
Tip: For loops that depend on convergence, add a safety limit on the number of iterations (
while abs(step) > tol && iterations < 100). A bad starting value or a bug then can't hang your program.
break: leave a loop early
break exits the innermost for or while loop immediately. It's the natural way to stop a search as soon as you find what you want:
readings = [12 15 14 19 23 31 28 35];
limit = 25;
for k = 1:numel(readings)
if readings(k) > limit
fprintf('First reading above %d: %d at position %d\n', limit, readings(k), k);
break
end
endFirst reading above 25: 31 at position 6
(The vectorised equivalent is find(readings > limit, 1).)
continue: skip to the next iteration
continue skips the rest of the current pass and goes on with the next one. Use it to ignore invalid items:
values = [4 -1 9 NaN 16 -4 25];
for v = values
if isnan(v) || v < 0
continue
end
fprintf('sqrt(%g) = %g\n', v, sqrt(v));
endsqrt(4) = 2
sqrt(9) = 3
sqrt(16) = 4
sqrt(25) = 5
Loops that must run at least once
MATLAB has no do ... while loop (Octave's do ... until is not MATLAB syntax). The usual pattern is while true with a break at the bottom:
% Collatz sequence: halve even numbers, map odd n to 3n+1, until reaching 1
n = 6;
sequence = n;
while true
if mod(n, 2) == 0
n = n / 2;
else
n = 3 * n + 1;
end
sequence(end+1) = n;
if n == 1
break
end
end
disp(sequence)
fprintf('%d steps\n', numel(sequence) - 1); 6 3 10 5 16 8 4 2 1
8 steps
sequence(end+1) = n appends to a vector. That's fine for short sequences whose length you can't know in advance; for long ones, preallocate if you can.
for or while?
| Situation | Loop |
|---|---|
| Visit every element / known number of steps | for |
| Repeat until a condition changes | while |
Stop a for loop early |
for + break |
| Run the body at least once | while true + break |
Test yourself
When is the condition of a while loop checked?
- Only once, at the start
- Before every iteration
- After every iteration
- Only when
breakis called
What does continue do?
- Exits the loop
- Skips the rest of the current iteration and starts the next
- Restarts the loop from the beginning
- Pauses the program
How do you write a loop that always runs at least once in MATLAB?
do ... whilerepeat ... untilwhile truewith abreakwhen donefor k = 1:Inf