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.
Think of a while-loop 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. Trace the execution 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 35. 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, we need N = k - 1 to get the correct count.

Checkpoint 36.

(a) While-loop condition timing.

When does MATLAB check the condition in a while-loop?
  • Before each iteration, including the first one.
  • MATLAB checks the condition before every iteration. If it’s false initially, the loop body never runs.
  • After each iteration completes.
  • The condition is checked before executing the loop body, not after.
  • Only once, at the start of the loop.
  • The condition is checked repeatedly before each iteration until it becomes false.
  • Only when the loop body updates a variable.
  • The condition is checked before each iteration regardless of what happens in the loop body.

(b) Avoiding infinite loops.

    To avoid an infinite loop, something inside the while-loop body must eventually make the condition false.
  • True.

  • If the condition never becomes false, the loop continues forever. You must update variables inside the loop to eventually satisfy the exit condition.
  • False.

  • If the condition never becomes false, the loop continues forever. You must update variables inside the loop to eventually satisfy the exit condition.

(c) While-loop as repeating if-statement.

    A while-loop can be thought of as a repeating if-statement that checks the condition, runs code if true, then checks again.
  • True.

  • This mental model helps understand how while-loops work: they repeatedly check and execute, just like an if-statement that repeats.
  • False.

  • This mental model helps understand how while-loops work: they repeatedly check and execute, just like an if-statement that repeats.

πŸ§‘πŸ»β€πŸ’» Class Activities πŸ§‘πŸ»β€πŸ’» Class Activities

These activities will help you practice using loops to solve interesting problems. Each activity requires only loops, variables, and basic arithmeticβ€”no arrays needed.

1. Approximating Pi with Leibniz’s Formula.

(a)
The Leibniz formula for \(\pi\) states that:
\begin{equation*} \frac{\pi}{4} = 1 - \frac{1}{3} + \frac{1}{5} - \frac{1}{7} + \frac{1}{9} - \cdots \end{equation*}
This infinite series converges slowly to \(\pi/4\text{,}\) but we can approximate it by adding many terms.
Write a MATLAB script that:
  1. Determines how many terms are needed to get within 0.001 of pi. Convert your for-loop version to a while-loop that stops when the error is small enough.
Hint: The denominators are odd numbers (1, 3, 5, 7, ...) which follow the pattern \(2k - 1\) when looping with k = 1:1000. Signs alternate, so use (-1)^(k+1) to generate the alternating signs.

2. The Collatz Conjecture.

(a)
The Collatz conjecture is one of mathematics’ most famous unsolved problems. Start with any positive integer n. If it is even, divide it by 2. If it is odd, multiply by 3 and add 1. Repeat this process until you reach 1.
For example, starting with 6:
\begin{gather*} 6 \to 3 \to 10 \to 5 \to 16 \to 8 \to 4 \to 2 \to 1 \end{gather*}
Write a MATLAB script that:
  1. Starts with a user-chosen positive integer n.
  2. Uses a while-loop to apply the Collatz rules repeatedly until reaching 1.
  3. Displays each number in the sequence.
  4. Reports how many steps it took to reach 1.
Hint.
Use mod(n, 2) == 0 to check if n is even. Keep a counter variable that increments each iteration.
(b)
Challenge: Test your script with different starting values. Can you find a starting number that takes more than 100 steps?

3. Digital Root Calculator.

(a)
The digital root of a number is found by repeatedly summing its digits until only a single digit remains. For example, the digital root of 9875 is found by:
\begin{gather*} 9 + 8 + 7 + 5 = 29\\ 2 + 9 = 11\\ 1 + 1 = 2 \end{gather*}
Write a MATLAB script that computes the digital root of any positive integer n using a while-loop. You can extract the rightmost digit of n using mod(n, 10), and remove it using floor(n/10).
Your script should:
  1. Accept a positive integer as input.
  2. Use an outer loop that repeats until n has only one digit.
  3. Use an inner loop to sum the digits of the current value of n.
  4. Display the digital root.
Hint.
Start with an outer loop: while n >= 10. Inside, use an inner loop to extract and sum digits, then update n to this sum.
(b)
Extension: Test your script with numbers like 38, 99, 123456, and 999999. What patterns do you notice?

4. Finding Fibonacci Numbers.

(a)
The Fibonacci sequence begins 0, 1, 1, 2, 3, 5, 8, 13, 21, ... where each number is the sum of the two preceding numbers.
Write a MATLAB script that:
  1. Uses a while-loop to generate Fibonacci numbers until one exceeds 10,000.
  2. Displays each Fibonacci number as it is computed.
  3. Reports which Fibonacci number was the first to exceed 10,000.
Hint: You only need three variables: the current Fibonacci number, the previous one, and the one before that. Use a pattern like:
prev2 = 0;
prev1 = 1;

while prev1 < 10000
		current = prev2 + prev1;
		% display and update variables
end
(b)
Extension: Modify your script to compute the ratio of consecutive Fibonacci numbers (e.g., \(F_n / F_{n-1}\)). What value does this ratio approach as \(n\) increases?

5. While-Loop Counter Drill.

Use the coding area, below, to complete the following tasks.
(a)
Use a while-loop to add the integers from 1 through 6 into total. Update total each pass and increment count so the loop eventually stops.
(b)
Change your loop so it adds the integers from 1 through 10 instead.

6. Doubling Value Drill.

Use the coding area, below, to complete the following tasks.
(a)
Write a while-loop that doubles value until it is at least 100. Increment steps by 1 each time the loop runs.
(b)
Change the starting value to a random integer between 1 and 8 using randi([1, 8]), then rerun the loop several times and compare the number of steps.

7. Build a Counting Function with a While-Loop.

(a)
Create a function named count_by that takes two scalar inputs, step and limit, and returns one scalar output lastValue. Start at 0 and repeatedly add step using a while-loop while lastValue + step <= limit.
(b)
Modify the function so it returns a second output numSteps that records how many loop iterations were used.
(c)
Test your function with a few scalar input pairs, such as (step, limit) = (4, 23) and (step, limit) = (7, 50). For these two tests, lastValue should be 20 and 49.

8. Points Game with if Inside a Loop.

(a)
Write a script that runs a while-loop for 12 rounds. Use a loop counter variable (for example round = 1) initialized before the loop, a condition like while round <= 12, and increment the counter each iteration. Each round generates a random scalar roll = randi([1, 12]).
(b)
Before the loop starts, initialize score = 0. Inside the loop, use an if-else statement: if mod(roll, 3) == 0, add 4 points to score; otherwise subtract 1 point.
(c)
Before the loop starts, initialize two scalar counters named bonusCount and penaltyCount to 0, then use them to track how many times each branch executes and finally display all three final values.

9. Mode Updates with switch Inside a Loop.

(a)
Write a script that runs a while-loop for exactly 15 iterations by using a loop counter. For example, start with iter = 0, use a condition like while iter < 15, and increment the counter each time with iter = iter + 1. In each iteration, generate a random mode code with mode = randi([1, 3]).
(b)
Before the loop begins, initialize a scalar energy (for example, energy = 0;). Then, inside the loop, use a switch-statement to update energy: add 2 when mode is 1, add 5 when mode is 2, and subtract 3 when mode is 3.
(c)
Add scalar counters mode1Count, mode2Count, and mode3Count to record how many times each case runs, and initialize these counters to 0 before the loop starts.

10. Combined switch and if in a Loop.

(a)
Start with scalar variables temp = 21 and minute = 1. Use a while-loop that runs while minute <= 10 (10 minutes of simulated time). In each iteration, generate mode = randi([0, 2]) where 0 = off, 1 = heat, and 2 = cool, then increment minute by 1.
(b)
Use a switch-statement on mode.
For heat mode, use an if-else: if temp < 20 increase temperature by 2, otherwise increase by 1.
For cool mode, if temp > 22 decrease by 2, otherwise decrease by 1. Off mode leaves temperature unchanged.
(c)
Before the loop, initialize scalar counters such as offCount = 0, heatCount = 0, and coolCount = 0. Inside the loop, update the appropriate counter each iteration based on mode, then after the loop display the final temperature and the three mode counts.