Skip to main content
Logo image

Exercises 💻 Coding Exercises

1. For-loop Exercises.

(a)

Write a function, sumSquares that computes
\begin{equation*} 1^2 + 2^2 + \cdots + n^2 \end{equation*}
for a given positive integer \(n\text{.}\)
Inputs:
n (1x1) double — positive integer
Outputs:
S (1x1) double — the sum \(1^2 + 2^2 + \cdots + n^2\)
Test cases:
% Test 1: Small value
n = 3;
% Run your script
% Expected: S = 14 (1^2 + 2^2 + 3^2 = 1 + 4 + 9)

% Test 2: Larger value
n = 5;
% Run your script
% Expected: S = 55 (1 + 4 + 9 + 16 + 25)

% Test 3: Edge case
n = 1;
% Run your script
% Expected: S = 1

% Test 4: Medium value
n = 10;
% Run your script
% Expected: S = 385

(b) Factorial Computation.

Write a script that computes the factorial of a number:
\begin{equation*} n! = 1 \cdot 2 \cdot \cdots \cdot n\text{.} \end{equation*}
Use a for loop. Assume \(n\) is a nonnegative integer. Store the result in F.
Inputs:
n (1x1) double — nonnegative integer
Outputs:
F (1x1) double — the factorial \(n!\)
Test cases:
% Test 1: Small factorial
n = 5;
% Run your script
% Expected: F = 120 (5! = 1*2*3*4*5)

% Test 2: Edge case
n = 0;
% Run your script
% Expected: F = 1 (0! = 1 by definition)

% Test 3: Another edge case
n = 1;
% Run your script
% Expected: F = 1

% Test 4: Larger value
n = 7;
% Run your script
% Expected: F = 5040

(c) Rewrite repeated output: counting by fives.

Rewrite the repeated code below as a for loop:
fprintf('5\n');
fprintf('10\n');
fprintf('15\n');
fprintf('20\n');
fprintf('25\n');
Your loop should produce the same output in the same order.

(d) Rewrite repeated output: countdown by twos.

Rewrite the repeated code below as a for loop:
fprintf('12\n');
fprintf('10\n');
fprintf('8\n');
fprintf('6\n');
fprintf('4\n');
fprintf('2\n');
Your loop should produce the same output in the same order.

(e) Rewrite repeated updates: total of 3 through 7.

Rewrite only the repeated update lines below as a for loop:
total = 0;
total = total + 3;
total = total + 4;
total = total + 5;
total = total + 6;
total = total + 7;
fprintf('total = %i\n', total);
Keep the initialization and final fprintf line.

(f) Exponential Series Partial Sum.

Let \(x\) be a real number. Use a for loop to compute the partial sum
\begin{equation*} \sum_{k=0}^{N} \frac{x^k}{k!} = 1 + \frac{x}{1!} + \frac{x^2}{2!} + \cdots + \frac{x^N}{N!} \end{equation*}
for a chosen integer \(N\text{.}\) Store the result in P.
Inputs:
x (1x1) double — real number
N (1x1) double — number of terms in the series (positive integer)
Outputs:
P (1x1) double — the partial sum
Test cases:
% Test 1: Simple case
x = 1;
N = 5;
% Run your script
% Expected: P ≈ 2.7167 (approximates e^1)

% Test 2: Zero input
x = 0;
N = 10;
% Run your script
% Expected: P = 1 (e^0 = 1)

% Test 3: Negative value
x = -1;
N = 10;
% Run your script
% Expected: P ≈ 0.3679 (approximates e^-1)

% Test 4: Larger N for better approximation
x = 2;
N = 20;
% Run your script
% Expected: P ≈ 7.3891 (approximates e^2)

(g) Die Rolling Simulation.

Simulate rolling a fair six-sided die \(N\) times. Use a for loop to count how many times you roll a 6. Store the count in sixes.
Inputs:
N (1x1) double — number of die rolls (positive integer)
Outputs:
sixes (1x1) double — count of how many times a 6 was rolled
Test cases:
% Test 1: Small number of rolls
rng(42);  % Set seed for reproducibility
N = 10;
% Run your script
% Expected: sixes will vary (typically 1-2)

% Test 2: Larger simulation
rng(123);
N = 100;
% Run your script
% Expected: sixes will vary (typically around 16-17)

% Test 3: Many rolls
rng(999);
N = 600;
% Run your script
% Expected: sixes will vary (typically around 100, which is 1/6 of 600)

(h) Powers of Two Display.

Write a script that uses a for loop to compute and display the first 10 powers of 2 (i.e., \(2^1, 2^2, \ldots, 2^{10}\)). For each iteration, use fprintf to display the exponent and result in the format: 2^n = result.
Inputs:
None (loop from 1 to 10)
Outputs:
Display to console — formatted output for each power
Test cases:
% Test: Run your script
% Expected output:
% 2^1 = 2
% 2^2 = 4
% 2^3 = 8
% 2^4 = 16
% 2^5 = 32
% 2^6 = 64
% 2^7 = 128
% 2^8 = 256
% 2^9 = 512
% 2^10 = 1024

(i) Running Products.

Write a script that uses a for loop to compute the running products \(1,\, 1 \cdot 2,\, 1 \cdot 2 \cdot 3,\, \ldots,\, 1 \cdot 2 \cdot \cdots \cdot N\text{.}\) Initialize a variable current_product to 1 before the loop, and create a vector running_product of length \(N\text{.}\) For each iteration \(k = 1, 2, \ldots, N\text{,}\) update current_product by multiplying it by \(k\text{,}\) then store the result in \(\texttt{running\_product(k)}\text{.}\) After the loop, display the contents of running_product.
Inputs:
N (1x1) double — positive integer for number of terms
Outputs:
running_product (1xN) double — vector of running products
Test cases:
% Test 1: Small value
N = 5;
% Run your script
% Expected: running_product = [1, 2, 6, 24, 120]

% Test 2: Edge case
N = 1;
% Run your script
% Expected: running_product = 1

% Test 3: Medium value
N = 7;
% Run your script
% Expected: running_product = [1, 2, 6, 24, 120, 720, 5040]

(j) Primality Test.

Write a script that tests whether a given positive integer number is prime. A number greater than 1 is prime if it has no divisors other than 1 and itself. By convention, 1 is not prime, so your script should set is_prime to \(false\) when number <= 1 and only run the divisor-testing loop when number > 1. Use a for loop to test all potential divisors from 2 to sqrt(number). Store the result in a logical variable is_prime (true if prime, false otherwise). Use mod(number, divisor) == 0 to check divisibility.
Inputs:
number (1x1) double — positive integer to test
Outputs:
is_prime (1x1) logical — true if number is prime, false otherwise
Test cases:
% Test 1: Prime number
number = 17;
% Run your script
% Expected: is_prime = true

% Test 2: Composite number
number = 15;
% Run your script
% Expected: is_prime = false

% Test 3: Edge case - 1 is not prime
number = 1;
% Run your script
% Expected: is_prime = false

% Test 4: Edge case - 2 is prime
number = 2;
% Run your script
% Expected: is_prime = true

% Test 5: Large prime
number = 97;
% Run your script
% Expected: is_prime = true

(k) Leibniz Pi Approximation.

Write a script that approximates \(\pi\) using the Leibniz formula:
\begin{equation*} \frac{\pi}{4} = 1 - \frac{1}{3} + \frac{1}{5} - \frac{1}{7} + \frac{1}{9} - \cdots \end{equation*}
Use a for loop to compute the sum of the first 1000 terms, then multiply by 4 to approximate \(\pi\text{.}\) Store the approximation in pi_approx. The denominators follow the pattern \(2k - 1\) and signs alternate (use (-1)^(k+1) for the sign).
Inputs:
None (fixed at 1000 terms)
Outputs:
pi_approx (1x1) double — approximation of \(\pi\)
Test cases:
% Test: Run your script with 1000 terms
% Expected: pi_approx ≈ 3.1406 (exact value depends on 1000 terms)
% Compare with MATLAB's built-in: pi
% Note: This is a slow-converging series, so it won't be very accurate

(l) Perfect Number Test.

Write a script that determines whether a given positive integer n is a perfect number. A perfect number equals the sum of its proper divisors (divisors excluding itself). Use a for loop to find all divisors from 1 to n-1, sum them, and compare to n. Store the result in a logical variable is_perfect. For example, 6 is perfect because \(1 + 2 + 3 = 6\text{.}\)
Inputs:
n (1x1) double — positive integer to test
Outputs:
is_perfect (1x1) logical — true if n is perfect, false otherwise
Test cases:
% Test 1: First perfect number
n = 6;
% Run your script
% Expected: is_perfect = true (1 + 2 + 3 = 6)

% Test 2: Second perfect number
n = 28;
% Run your script
% Expected: is_perfect = true (1 + 2 + 4 + 7 + 14 = 28)

% Test 3: Not perfect
n = 10;
% Run your script
% Expected: is_perfect = false (1 + 2 + 5 = 8 ≠ 10)

% Test 4: Small non-perfect
n = 12;
% Run your script
% Expected: is_perfect = false

(m) Sum of Odd Numbers.

Write a script that uses a for loop to compute the sum of all odd numbers from 1 to N (where N is given). Use the loop to iterate through the range 1:2:N, which generates only odd numbers. Store the result in sum_odd.
Inputs:
N (1x1) double — positive integer upper limit
Outputs:
sum_odd (1x1) double — sum of all odd numbers from 1 to N
Test cases:
% Test 1: Small range
N = 9;
% Run your script
% Expected: sum_odd = 25 (1 + 3 + 5 + 7 + 9)

% Test 2: Even upper limit
N = 10;
% Run your script
% Expected: sum_odd = 25 (1 + 3 + 5 + 7 + 9, stops before 10)

% Test 3: Larger range
N = 20;
% Run your script
% Expected: sum_odd = 100 (1 + 3 + 5 + ... + 19)

% Test 4: Edge case
N = 1;
% Run your script
% Expected: sum_odd = 1

2. While-loop Exercises.

(a) Doubling Until Threshold.

Write a script that starts with num = 1 and uses a while loop to repeatedly double num until it exceeds 1000. After the loop, display the final value of num using fprintf.
Inputs:
None (starts with num = 1)
Outputs:
num (1x1) double — first value that exceeds 1000
Test cases:
% Test: Run your script
% Expected: num = 1024
% (Sequence: 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024)

(b) Harmonic Sum Threshold.

Write a script that computes the smallest integer \(N\) such that the harmonic sum
\begin{equation*} \frac{1}{1} + \frac{1}{2} + \frac{1}{3} + \cdots + \frac{1}{N} \ge 5 \end{equation*}
Use a while loop to add terms until the sum reaches or exceeds 5. Store the final value of \(N\) in a variable named N and the sum in harmonic_sum.
Inputs:
None (start with N = 0 and harmonic_sum = 0)
Outputs:
N (1x1) double — smallest integer for which harmonic sum \(\ge 5\)
harmonic_sum (1x1) double — the harmonic sum
Test cases:
% Test: Run your script
% Expected: N = 83 (approximately)
%           harmonic_sum ≈ 5.0021

(c) Collatz Conjecture.

Write a script that implements the Collatz conjecture for a given positive integer n. The rules are: if n is even, divide by 2; if n is odd, multiply by 3 and add 1. Use a while loop to repeat until n reaches 1. Count the number of steps required and store it in a variable named steps. Use mod(n, 2) == 0 to test if n is even.
Inputs:
n (1x1) double — positive integer
Outputs:
steps (1x1) double — number of steps to reach 1
Test cases:
% Test 1: Small value
n = 6;
% Run your script
% Expected: steps = 8
% (Sequence: 6 → 3 → 10 → 5 → 16 → 8 → 4 → 2 → 1)

% Test 2: Another small value
n = 10;
% Run your script
% Expected: steps = 6

% Test 3: Edge case
n = 1;
% Run your script
% Expected: steps = 0

% Test 4: Larger value
n = 27;
% Run your script
% Expected: steps = 111

(d) Digital Root.

Write a script that computes the digital root of a positive integer n. The digital root is found by repeatedly summing the digits until only a single digit remains.
Use an outer while loop that continues as long as n >= 10. Inside this loop: first set a variable (for example, sum_digits) to 0. Then copy n into a temporary variable (for example, temp) and use an inner while loop that runs while temp > 0. In the inner loop, extract the rightmost digit with mod(temp, 10), add it to sum_digits, and then update temp using floor(temp/10) to remove the rightmost digit. After the inner loop finishes, assign n = sum_digits and repeat the outer loop test. When the outer loop ends, store the final single-digit value of n in digital_root.
Inputs:
n (1x1) double — positive integer
Outputs:
digital_root (1x1) double — single digit (0-9)
Test cases:
% Test 1: Multi-digit number
n = 38;
% Run your script
% Expected: digital_root = 2
% (38 → 3+8=11 → 1+1=2)

% Test 2: Another example
n = 987;
% Run your script
% Expected: digital_root = 6
% (987 → 9+8+7=24 → 2+4=6)

% Test 3: Single digit
n = 7;
% Run your script
% Expected: digital_root = 7

% Test 4: Larger number
n = 12345;
% Run your script
% Expected: digital_root = 6
% (12345 → 1+2+3+4+5=15 → 1+5=6)

(e) Fibonacci Threshold.

Write a script that uses a while loop to generate Fibonacci numbers until one exceeds 10000. The Fibonacci sequence starts with 0 and 1, and each subsequent number is the sum of the two preceding numbers. Store the first Fibonacci number that exceeds 10000 in fib_result. You will need variables for the current number and the two previous numbers.
Inputs:
None (start sequence with 0 and 1)
Outputs:
fib_result (1x1) double — first Fibonacci number exceeding 10000
Test cases:
% Test: Run your script
% Expected: fib_result = 10946
% (Sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21, ..., 6765, 10946)