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.
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.
π§π»βπ» 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.
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.
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.
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:
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).
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?
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.
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.
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]).
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.
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.
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]).
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.
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.
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.
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.