Skip to main content
Logo image

Subsection The while Loop

Sometimes you need to repeat code until a specific condition changes, but you do not know in advance how many iterations that will take. For example, suppose you want to double a number until it exceeds 1000:
num = 1;

num = num * 2;  % 2
num = num * 2;  % 4
num = num * 2;  % 8
num = num * 2;  % 16
num = num * 2;  % 32
num = num * 2;  % 64
num = num * 2;  % 128
num = num * 2;  % 256
num = num * 2;  % 512
num = num * 2;  % 1024

fprintf('Final value: %i\n', num)
num = 1;

while num <= 1000
    num = num * 2;
end

fprintf('Final value: %i\n', num)
The loop version automatically stops when num exceeds 1000. Without a loop, you must manually count iterations and hope you wrote enough (or not too many) doubling operations. If you change the starting value or the threshold, the loop still works without modification, but the explicit version would need rewriting.
A good way to understand a while-loop is to think of it as a repeating if-statement. It checks the condition, runs the code if true, then checks again, and so on until the condition becomes false.
With an if-statement ‡︎
num = 5;

if num <= 50
    num = num * 2;
end
num = 5 β†’ 10.
With a while-Loop ‡︎
num = 5;

while num <= 50
    num = num * 2;
end
num: 5 β†’ 10 β†’ 20 β†’ 40 β†’ 80.

while-Loop Structure.

The basic syntax is:
while loop_condition
    code_block
end
MATLAB repeatedly executes code_block as long as loop_condition evaluates to true. Think of it like an if-statement that jumps back to the top and checks the condition again.
Key requirements:
  • The condition must be true initially, or the loop body never runs.
  • Something inside the loop must eventually make the condition false, or you create an infinite loop.
  • Every while-loop must end with end.
If MATLAB becomes unresponsive due to an infinite loop, press Ctrl+C (Windows) or Command+C (Mac) to stop execution.
Here is a simple example you can trace by hand:
While loop ‡︎
loop = 0;
x = 10;

while loop < 2
    loop = loop + 1;
    x = 2*(x + loop);
end

ratio = x/loop
Written out ‡︎
loop = 0
x = 10

(is loop < 2? Yes β†’ enter while)
	loop = 0 + 1 = 1
	x = 2*(10 + 1) = 22
(is loop < 2? Yes β†’ enter while again)	
	loop = 1 + 1 = 2
	x = 2*(22 + 2) = 48
(is loop < 2? No β†’ exit while)

ratio = 48/2 = 24

🌌 Example 34. Example: Summing Until a Threshold.

Find the first integer \(N\) such that
\begin{equation*} \frac{1}{1}+\frac{1}{2}+\frac{1}{3}+\cdots+\frac{1}{N} \ge 10\text{.} \end{equation*}
the_sum = 0;
k = 1;

while the_sum < 10
	the_sum = the_sum + 1/k;
	k = k + 1;
end

N = k - 1
the_sum
The loop adds terms until the sum crosses 10. Since k is incremented after adding each term, the first β€œsuccessful” value is N = k - 1.