Skip to main content
Logo image

Subsection The for Loop

Imagine you want to print the message β€œHello!” five times. Without loops, you would write the same command repeatedly. With a loop, it is much cleaner:
Without a loop ‡︎
fprintf('Hello!\n')
fprintf('Hello!\n')
fprintf('Hello!\n')
fprintf('Hello!\n')
fprintf('Hello!\n')
With a loop ‡︎
for i = 1:5
		fprintf('Hello!\n')
end
The for-loop version is shorter, clearer, and easier to modify. If you later need 100 repetitions instead of 5, you only change one number rather than copying and pasting 95 more lines.

for-Loop Structure.

There are two basic options for defining a for loop in MATLAB:
% Fixed range with step size
for k = start:step:stop
	blockToRepeat
end
% Explicit list of values
for k = [v1, v2, v3, ... vn]
	blockToRepeat
end
Key rules:
  • The variable k is called the loop variable or loop index and can be named anything.
  • The loop automatically updates k to the next value after each iteration.
  • Every for-loop must end with end.
  • You can place any code inside a loop, including other loops.
Table 31. Sample Usage of start:step:stop When you don’t specify a step, it defaults to 1.
Expression Resulting List
1:10 [1, 2, 3, ..., 10]
1:2:10 [1, 3, 5, 7, 9]
1:n [1, 2, 3, ..., n]
n:-1:1 [n, n-1, n-2, ..., 1]
0.5:0.5:2 [0.5, 1.0, 1.5, 2.0]
Here is a concrete example showing repeated calculations. Suppose you want to compute and display several powers of 2. Without a loop, you must explicitly write each calculation:
Without Loops ‡︎
n = 1;
x = 2^n;
fprintf('2^%i = %i\n', n, x)

n = 2;
x = 2^n;
fprintf('2^%i = %i\n', n, x)

n = 3;
x = 2^n;
fprintf('2^%i = %i\n', n, x)

n = 4;
x = 2^n;
fprintf('2^%i = %i\n', n, x)

n = 5;
x = 2^n;
fprintf('2^%i = %i\n', n, x)
With a for-Loop ‡︎
for n = 1:5
	x = 2^n;
	fprintf('2^%i = %i\n', n, x)
end
Both versions produce the same output: 2^1 = 2, 2^2 = 4, 2^3 = 8, 2^4 = 16, and 2^5 = 32. The loop version eliminates redundancy by automatically updating the loop variable n from 1 to 5.

🌌 Example 32. Accumulating a Sum.

A common loop pattern is accumulation: start with an initial value, then repeatedly update it. Also known as a running sum. Here we compute the sum \(1+2+3+4+5\text{:}\)
totalSum = 0; % initialize
for i = 1:5
	totalSum = totalSum + i;
end
fprintf('Total Sum: %i\n', totalSum)
Here, totalSum starts at 0, then increases by 1, then 2, and so on, reaching 15.
Expanded loop for the accumulation of totalSum ‡︎
totalSum = 0;
i = 1;
totalSum = totalSum + i;   % = 0 + 1 = 1;
i = 2;
totalSum = totalSum + i;   % = 1 + 2 = 3;
i = 3;
totalSum = totalSum + i;   % = 3 + 3 = 6;
i = 4;
totalSum = totalSum + i;   % = 6 + 4 = 10;
i = 5;
totalSum = totalSum + i;   % = 10 + 5 = 15;

🌌 Example 33. Factorial.

This example shows another accumulation pattern: a running product, called a factorial:
\begin{equation*} n! = 1 \cdot 2 \cdot 3 \cdots n\text{.} \end{equation*}
Loop version ‡︎
n = 6; % Compute 6! 

factorial = 1; % initialize
for k = 1:n
	factorial = factorial * k;
end
fprintf('%i! = %i\n', n, factorial)
Expanded version ‡︎
factorial = 1; % initial
factorial = 1 * 1 = 1;
factorial = 1 * 2 = 2;
factorial = 2 * 3 = 6;
factorial = 6 * 4 = 24;
factorial = 24 * 5 = 120;
factorial = 120 * 6 = 720;
After the loop completes, factorial holds \(1\cdot 2\cdot\cdots\cdot 6=720\) (\(6!\)).

Checkpoint 34.

(a) The loop variable is automatically updated.

    In a for-loop, the loop variable is automatically updated to the next value after each iteration.
  • True.

  • MATLAB handles the loop variable update automatically, so you don’t need to manually increment it.
  • False.

  • MATLAB handles the loop variable update automatically, so you don’t need to manually increment it.

(b) What does 5:2:15 produce?

What list of values does 5:2:15 produce?
  • [5, 7, 9, 11, 13, 15]
  • Correct! The loop starts at 5, adds 2 each time, and stops at or before 15.
  • [5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
  • This would be 5:15 (step size defaults to 1 when omitted).
  • [5, 10, 15]
  • This would be 5:5:15 with a step size of 5, not 2.
  • [2, 4, 6, 8, 10, 12, 14]
  • The start value is 5, not 2. This would be 2:2:14.

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

These activities will help you practice using for-loops to solve interesting problems.

1. Rewrite the Repeated Code.

For each of the following code snippets, rewrite the repeated lines using a for-loop.
(a)
fprintf('2^1 = 2\n');
fprintf('2^2 = 4\n');
fprintf('2^3 = 8\n');
fprintf('2^4 = 16\n');
fprintf('2^5 = 32\n');
Solution.
for n = 1:5
	x = 2^n;
	fprintf('2^%i = %i\n', n, x)
end
(b)
total = 0;
total = total + 2;
total = total + 4;
total = total + 6;
total = total + 8;
total = total + 10;
fprintf('total = %i\n', total);
Solution.
total = 0;
for k = 2:2:10
	total = total + k;
end
fprintf('total = %i\n', total);
(c)
n = 4;
x = 1 - 3^2;
x = 2 - 4^3;
x = 3 - 5^4;
x = 4 - 6^5;
fprintf('x = %i\n', x);
Solution.
n = 4;
for k = 1:n
	x = k - (k+2)^(k+1);
end
fprintf('x = %i\n', x);
(d)
n = 6;
x = 10;
x = 10 - 3;
x = 7 - 3;
x = 4 - 3;
x = 1 - 3;
x = -2 - 3;
fprintf('x = %i\n', x);
Solution.
n = 6;
x = 10;
for k = 1:n
	x = x - 3;
end
fprintf('x = %i\n', x);

2. Counting with a Loop.

Give a for-loop that produces each of the given outputs (use fprintf).
(a)
1-one-thousand
2-one-thousand
3-one-thousand
4-one-thousand
5-one-thousand
Solution.
for k = 1:5
	fprintf('%i-one-thousand\n', k);
end
(b)
3
6								
9						
12
15
18
Solution.
for k = 3:3:18
	fprintf('%i\n', k);
end
(c)
10, 9, 8, 7, 6, 5, 4, 3, 2, 1, boom!
Solution.
for k = 10:-1:1
	fprintf('%i, ', k);
end
fprintf('boom!\n');

3. Compute the Running Total.

For each of the following, assume that:
  • a is a random integer between 100 and 900, and
  • x is a random integer between 5 and 12
and write a for-loop that completes each task.
(a)
Compute the sum of all integers between x and a. Store the result in total.
(b)
Compute the sum of all integers between 0 and a that are divisible by x. Store the result in total.

4. Approximating Pi with Leibniz’s Formula.

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. Work through the tasks below to approximate \(\pi\text{.}\)
(a)
Write a for-loop that computes the first 10 terms of the sum:
\begin{equation*} 1 + \frac{1}{2} + \frac{1}{3} + \frac{1}{4} + \cdots\text{.} \end{equation*}
Store the result in a variable called approx and print its value.
(b)
Update the for-loop so that it computes the first 10 terms of the sum:
\begin{equation*} \frac12 + \frac14 + \frac16 + \cdots\text{.} \end{equation*}
Store the result in a variable called total and print its value.
(c)
Update the for-loop so that it computes the first 10 terms of the sum:
\begin{equation*} \frac11 + \frac13 + \frac15 + \frac17 + \cdots\text{.} \end{equation*}
Store the result in a variable called total and print its value.
Hint.
The denominators are odd numbers \((1, 3, 5, 7, ...)\) which are just the even numbers minus 1.
(d)
Update the for-loop so that it computes the first 10 terms of the sum:
\begin{equation*} 1 - \frac{1}{3} + \frac{1}{5} - \frac{1}{7} + \cdots\text{.} \end{equation*}
Store the result in a variable called total.
Hint.
To get alternating signs, think about multiplying by -1 to an even or odd power.
(e)
Use the for loop in the previous task, to approximate pi using Leibniz formula:
\begin{equation*} \frac{\pi}{4} = 1 - \frac{1}{3} + \frac{1}{5} - \frac{1}{7} + \frac{1}{9} - \cdots\text{.} \end{equation*}
Store the approximation in a variable called approx.
Additionally, print the value of approx, pi, and abs(pi - approx).

5. Counting Heads.

(a)
Write a function, called headsCount, that uses a for loop to count the number of heads that result from flipping a coin n times. Inside the loop, simulate a single coin flip using randi([0,1]), where 0 represents tails and 1 represents heads.
(b)
Extend your function to count the number of times you get two heads in a row.
(c)
Finally, update your function to estimate the probability of getting two heads in a row.

6. Number Classifier.

A proper divisor of a positive integer is any positive integer less than the number itself that divides it evenly. For example, the proper divisors of 12 are 1, 2, 3, 4, and 6.
In this exercise, you will write a MATLAB function to determine whether a given positive integer is one of the following:
Perfect Number
equals the sum of its proper divisors. For example, 6 is perfect because \(1 + 2 + 3 = 6\text{.}\)
Deficient Number
greater than the sum of its proper divisors. For example, 8 is deficient because \(1 + 2 + 4 = 7 < 8\text{.}\)
Abundant Number
less than the sum of its proper divisors. For example, 12 is abundant since \(1 + 2 + 3 + 4 + 6 = 16 > 12\text{.}\)
(a)
Write a MATLAB function, called sumProperDivisors, that computes the sum of the proper divisors of a given positive integer, \(n\text{.}\) Use a for-loop and the mod function.
(b)
Write a MATLAB function, called classifyNumber, that classifies a given positive integer as "perfect", "abundant", or "deficient". Use the function from the previous task as a helper function. You should not need a loop in this function.