Skip to main content
Logo image

Exercises 2.6 πŸ’» Coding Problems

1. Simple Programs (Variables, Functions, and Scripts).

Answer the following questions to check your understanding of functions.

(a) Temperature Conversion.

Write a function named celsius_to_fahrenheit that converts a temperature from Celsius to Fahrenheit.
The conversion formula is: \(F = \frac{9}{5}C + 32\)
Inputs:
celsius (1x1) double β€” temperature in degrees Celsius
Outputs:
fahrenheit (1x1) double β€” temperature in degrees Fahrenheit
Test cases:
% Test 1: Freezing point of water
f1 = celsius_to_fahrenheit(0)
% Expected: f1 = 32

% Test 2: Boiling point of water
f2 = celsius_to_fahrenheit(100)
% Expected: f2 = 212

% Test 3: Room temperature
f3 = celsius_to_fahrenheit(20)
% Expected: f3 = 68

(b) Triangle Area.

Write a function named triangle_area that computes the area of a triangle given its base and height.
The area formula is: \(A = \frac{1}{2} \times \text{base} \times \text{height}\)
Inputs:
base (1x1) double β€” length of the triangle’s base
height (1x1) double β€” height of the triangle
Outputs:
area (1x1) double β€” area of the triangle
Test cases:
% Test 1: Simple triangle
a1 = triangle_area(6, 4)
% Expected: a1 = 12

% Test 2: Right triangle
a2 = triangle_area(5, 12)
% Expected: a2 = 30

% Test 3: Decimal values
a3 = triangle_area(7.5, 3.2)
% Expected: a3 = 12

(c) Sphere Properties.

Write a function named sphere_properties that computes both the surface area and volume of a sphere given its radius.
The formulas are:
Inputs:
radius (1x1) double β€” radius of the sphere
Outputs:
surface_area (1x1) double β€” surface area of the sphere
volume (1x1) double β€” volume of the sphere
Test cases:
% Test 1: Unit sphere
[A1, V1] = sphere_properties(1)
% Expected: A1 β‰ˆ 12.5664, V1 β‰ˆ 4.1888

% Test 2: Radius of 2
[A2, V2] = sphere_properties(2)
% Expected: A2 β‰ˆ 50.2655, V2 β‰ˆ 33.5103

% Test 3: Radius of 5
[A3, V3] = sphere_properties(5)
% Expected: A3 β‰ˆ 314.1593, V3 β‰ˆ 523.5988

(d) Cylinder Properties.

Write a function named cylinder_properties that computes the surface area, volume, and diagonal of a cylinder given its radius and height.
The formulas are:
Part of this problem is determining the correct formula for the diagonal of a cylinder. Hint: take out a piece of paper and sketch the cylinder, then draw the diagonal line from one edge of the base to the opposite edge of the top.
Inputs:
radius (1x1) double β€” radius of the cylinder
height (1x1) double β€” height of the cylinder
Outputs:
surface_area (1x1) double β€” total surface area of the cylinder
volume (1x1) double β€” volume of the cylinder
diagonal (1x1) double β€” diagonal length
Test cases:
% Test 1: Unit cylinder (radius = 1, height = 1)
[A1, V1, d1] = cylinder_properties(1, 1)
% Expected: A1 β‰ˆ 12.5664, V1 β‰ˆ 3.1416, d1 β‰ˆ 2.2361

% Test 2: Radius = 3, height = 5
[A2, V2, d2] = cylinder_properties(3, 5)
% Expected: A2 β‰ˆ 150.7964, V2 β‰ˆ 141.3717, d2 β‰ˆ 7.8102

% Test 3: Radius = 2.5, height = 8
[A3, V3, d3] = cylinder_properties(2.5, 8)
% Expected: A3 β‰ˆ 164.9336, V3 β‰ˆ 157.0796, d3 β‰ˆ 9.4340

(e) Compound Interest Calculator.

Write a function named compound_interest that calculates the future value of an investment with compound interest, and also returns the total interest earned and the effective annual rate.
The compound interest formula is: \(A = P\left(1 + \frac{r}{n}\right)^{nt}\)
where:
The effective annual rate (EAR) is: \(\text{EAR} = \left(1 + \frac{r}{n}\right)^n - 1\)
Inputs:
principal (1x1) double β€” initial investment amount
rate (1x1) double β€” annual interest rate (as decimal)
compounds_per_year (1x1) double β€” compounding frequency (e.g., 12 for monthly)
years (1x1) double β€” time period in years
Outputs:
final_amount (1x1) double β€” total amount after compound interest
interest_earned (1x1) double β€” total interest earned (final_amount - principal)
effective_rate (1x1) double β€” effective annual rate
Test cases:
% Test 1: $1000 at 5% annual rate, compounded monthly for 10 years
[final1, int1, effRate1] = compound_interest(1000, 0.05, 12, 10)
% Expected: final1 β‰ˆ 1647.01, int1 β‰ˆ 647.01, effRate1 β‰ˆ 0.0512

% Test 2: $5000 at 3% annual rate, compounded quarterly for 5 years
[final2, int2, effRate2] = compound_interest(5000, 0.03, 4, 5)
% Expected: final2 β‰ˆ 5805.92, int2 β‰ˆ 805.92, effRate2 β‰ˆ 0.03034

% Test 3: $10000 at 6% annual rate, compounded daily for 20 years
[final3, int3, effRate3] = compound_interest(10000, 0.06, 365, 20)
% Expected: final3 β‰ˆ 33197.90, int3 β‰ˆ 23197.90, effRate3 β‰ˆ 0.0618

(f) Triangle Perimeter and Area in 3D Space.

Write a function named triangle_3d that computes the perimeter and area of a triangle in 3D space given the coordinates of its three vertices. You may assume the three points do not lie on the same straight line. This ensures a valid triangle.
Hints:
  1. The distance formula between two points \((x_1, y_1, z_1)\) and \((x_2, y_2, z_2)\) is:
    \begin{equation*} d = \sqrt{(x_2 - x_1)^2 + (y_2 - y_1)^2 + (z_2 - z_1)^2} \end{equation*}
  2. If the side lengths of the triangle are \(a\text{,}\) \(b\text{,}\) and \(c\text{,}\) then the area is given by Heron’s formula:
    \begin{equation*} A = \sqrt{s(s-a)(s-b)(s-c)} \end{equation*}
    where \(s = 0.5\left(a+b+c\right)\) (known as the semi-perimeter).
Inputs:
x1, y1, z1 (1x1) double β€” coordinates of first vertex
x2, y2, z2 (1x1) double β€” coordinates of second vertex
x3, y3, z3 (1x1) double β€” coordinates of third vertex
Outputs:
perimeter (1x1) double β€” perimeter of the triangle
area (1x1) double β€” area of the triangle
Note: Typically you would pass coordinates as vectors or matrices, but we will save that for later exercises.
Test cases:
% Test 1: Triangle in xy-plane (vertices at (0,0,0), (4,0,0), (0,3,0))
[p1, a1] = triangle_3d(0, 0, 0, 4, 0, 0, 0, 3, 0)
% Expected: p1 = 12, a1 = 6 (3-4-5 right triangle)

% Test 2: Equilateral triangle in space
[p2, a2] = triangle_3d(0, 0, 0, 1, 0, 0, 0.5, sqrt(3)/2, 0)
% Expected: p2 = 3, a2 β‰ˆ 0.4330

% Test 3: Triangle with vertices at (1,2,3), (4,5,6), (2,3,5)
[p3, a3] = triangle_3d(1, 2, 3, 4, 5, 6, 2, 3, 5)
% Expected: p3 β‰ˆ 10.6456, a3 β‰ˆ 2.1213

2. Conditional Flow (if and switch statements).

(a) Number in Range.

Write a function named is_in_range that determines whether a number falls within a specified range (inclusive).
Inputs:
value (1x1) double β€” the number to check
lower_bound (1x1) double β€” minimum value of the range
upper_bound (1x1) double β€” maximum value of the range
Outputs:
result (1x1) logical β€” true if value is in range [lower_bound, upper_bound], false otherwise
Test cases:
% Test 1: Value in range
r1 = is_in_range(5, 1, 10)
% Expected: r1 = 1 (true)

% Test 2: Value at lower boundary
r2 = is_in_range(1, 1, 10)
% Expected: r2 = 1 (true)

% Test 3: Value at upper boundary
r3 = is_in_range(10, 1, 10)
% Expected: r3 = 1 (true)

% Test 4: Value below range
r4 = is_in_range(0, 1, 10)
% Expected: r4 = 0 (false)

% Test 5: Value above range
r5 = is_in_range(11, 1, 10)
% Expected: r5 = 0 (false)

(b) Tax Bracket Rate Finder.

Write a function named find_tax_rate that determines the marginal tax rate for a given income based on progressive tax brackets.
Tax bracket rates:
Inputs:
income (1x1) double β€” annual income in dollars
Outputs:
tax_rate (1x1) double β€” the marginal tax rate (as a decimal, e.g., 0.10 for 10%)
Test cases:
% Test 1: No tax bracket
t1 = find_tax_rate(8000)
% Expected: t1 = 0

% Test 2: 10% bracket
t2 = find_tax_rate(25000)
% Expected: t2 = 0.10

% Test 3: 15% bracket
t3 = find_tax_rate(60000)
% Expected: t3 = 0.15

% Test 4: 20% bracket
t4 = find_tax_rate(100000)
% Expected: t4 = 0.20

% Test 5: Boundary case
t5 = find_tax_rate(40000)
% Expected: t5 = 0.10

(c) Water Phase Identifier.

Write a function named water_phase that determines the physical state of water (ice, liquid, or steam) based on temperature in Celsius at standard atmospheric pressure.
Phase rules:
Inputs:
temp_celsius (1x1) double β€” temperature in Celsius
Outputs:
phase (1x1) string β€” "ice", "liquid", or "steam"
Test cases:
% Test 1: Below freezing
p1 = water_phase(-10)
% Expected: p1 = "ice"

% Test 2: Freezing point
p2 = water_phase(0)
% Expected: p2 = "liquid"

% Test 3: Room temperature
p3 = water_phase(25)
% Expected: p3 = "liquid"

% Test 4: Boiling point
p4 = water_phase(100)
% Expected: p4 = "liquid"

% Test 5: Above boiling
p5 = water_phase(120)
% Expected: p5 = "steam"

(d) BMI Category Classifier.

Write a function named bmi_category that calculates Body Mass Index (BMI) and classifies it into standard health categories.
BMI is calculated as: \(\text{BMI} = \frac{\text{weight (kg)}}{\text{height (m)}^2}\)
Categories:
Inputs:
weight_kg (1x1) double β€” weight in kilograms
height_m (1x1) double β€” height in meters
Outputs:
category (1x1) string β€” the BMI category
Test cases:
% Test 1: Underweight
c1 = bmi_category(50, 1.75)
% Expected: c1 = "Underweight"

% Test 2: Normal weight
c2 = bmi_category(70, 1.75)
% Expected: c2 = "Normal weight"

% Test 3: Overweight
c3 = bmi_category(85, 1.75)
% Expected: c3 = "Overweight"

% Test 4: Obese
c4 = bmi_category(100, 1.75)
% Expected: c4 = "Obese"

% Test 5: Boundary case
c5 = bmi_category(75.5, 1.75)
% Expected: c5 = "Normal weight"

(e) Even and Positive.

Write a function named is_even_and_positive that determines whether a number is both even and positive.
A number is even if dividing it by 2 produces no remainder. You can use the mod function to find remainders.
Inputs:
num (1x1) double β€” the number to check
Outputs:
result (1x1) logical β€” true if num is both even and positive, false otherwise
Test cases:
% Test 1: Even and positive
r1 = is_even_and_positive(4)
% Expected: r1 = 1 (true)

% Test 2: Odd and positive
r2 = is_even_and_positive(7)
% Expected: r2 = 0 (false)

% Test 3: Even and negative
r3 = is_even_and_positive(-6)
% Expected: r3 = 0 (false)

% Test 4: Zero (even but not positive)
r4 = is_even_and_positive(0)
% Expected: r4 = 0 (false)

% Test 5: Large even positive
r5 = is_even_and_positive(100)
% Expected: r5 = 1 (true)

(f) Exclusive OR (XOR).

Write a function named my_xor that implements the exclusive OR operation without using MATLAB’s built-in xor function.
XOR returns true when exactly one (but not both) of the inputs is true. Think about how you can combine AND, OR, and NOT operators to achieve this behavior.
Inputs:
a (1x1) logical β€” first logical value
b (1x1) logical β€” second logical value
Outputs:
result (1x1) logical β€” true if exactly one input is true, false otherwise
Test cases:
% Test 1: Both false
r1 = my_xor(false, false)
% Expected: r1 = 0 (false)

% Test 2: First true, second false
r2 = my_xor(true, false)
% Expected: r2 = 1 (true)

% Test 3: First false, second true
r3 = my_xor(false, true)
% Expected: r3 = 1 (true)

% Test 4: Both true
r4 = my_xor(true, true)
% Expected: r4 = 0 (false)

(g) Parking Fee Calculator.

Write a function named parking_fee that calculates the parking fee based on the number of hours parked.
Fee structure:
Note: Use the ceil function to round up partial hours. For example, ceil(2.3) returns 3.
Inputs:
hours (1x1) double β€” number of hours parked (may include fractions)
Outputs:
fee (1x1) double β€” total parking fee in dollars
Test cases:
% Test 1: First hour
f1 = parking_fee(0.5)
% Expected: f1 = 3

% Test 2: Two hours
f2 = parking_fee(2)
% Expected: f2 = 5 (3 + 2)

% Test 3: Four hours
f3 = parking_fee(4)
% Expected: f3 = 9 (3 + 2 + 2 + 2)

% Test 4: Six hours
f4 = parking_fee(6)
% Expected: f4 = 12 (3 + 2 + 2 + 2 + 1.5 + 1.5)

% Test 5: Exceeds maximum
f5 = parking_fee(12)
% Expected: f5 = 15

(h) Rock-Paper-Scissors Judge.

Write a function named rps_winner that determines the winner of a rock-paper-scissors game. Use a switch statement to handle the different move combinations.
Rules:
Moves are represented as: ’R’ for rock, ’P’ for paper, ’S’ for scissors.
Inputs:
player1 (1x1) char β€” player 1’s move (’R’, ’P’, or ’S’)
player2 (1x1) char β€” player 2’s move (’R’, ’P’, or ’S’)
Outputs:
result (1x1) string β€” "Player 1", "Player 2", or "Tie"
Test cases:
% Test 1: Rock beats Scissors
r1 = rps_winner('R', 'S')
% Expected: r1 = "Player 1"

% Test 2: Paper beats Rock
r2 = rps_winner('R', 'P')
% Expected: r2 = "Player 2"

% Test 3: Scissors beats Paper
r3 = rps_winner('S', 'P')
% Expected: r3 = "Player 1"

% Test 4: Tie
r4 = rps_winner('R', 'R')
% Expected: r4 = "Tie"

% Test 5: Another scenario
r5 = rps_winner('P', 'S')
% Expected: r5 = "Player 2"

(i) Hurricane Category Classifier.

Write a function named hurricane_category that classifies a hurricane based on its wind speed using the Saffir-Simpson scale.
Categories (based on sustained wind speed in mph):
Inputs:
wind_speed (1x1) double β€” sustained wind speed in mph
Outputs:
category (1x1) string β€” the hurricane category
Test cases:
% Test 1: Tropical Storm
c1 = hurricane_category(60)
% Expected: c1 = "Tropical Storm"

% Test 2: Category 1
c2 = hurricane_category(85)
% Expected: c2 = "Category 1"

% Test 3: Category 3
c3 = hurricane_category(120)
% Expected: c3 = "Category 3"

% Test 4: Category 5
c4 = hurricane_category(160)
% Expected: c4 = "Category 5"

% Test 5: Boundary case
c5 = hurricane_category(74)
% Expected: c5 = "Category 1"

(j) Zodiac Sign Finder.

Write a function named zodiac_sign that determines a person’s Western zodiac sign based on their birth month and day. Use a switch statement for the month, then if statements for the day ranges.
Zodiac date ranges (using format: month number, day range):
Inputs:
month (1x1) double β€” birth month (1-12)
day (1x1) double β€” birth day (1-31)
Outputs:
sign (1x1) string β€” zodiac sign name
Test cases:
% Test 1: Early January (Capricorn)
z1 = zodiac_sign(1, 10)
% Expected: z1 = "Capricorn"

% Test 2: Late January (Aquarius)
z2 = zodiac_sign(1, 25)
% Expected: z2 = "Aquarius"

% Test 3: Mid-year (Leo)
z3 = zodiac_sign(8, 5)
% Expected: z3 = "Leo"

% Test 4: Boundary case (Taurus/Gemini)
z4 = zodiac_sign(5, 20)
% Expected: z4 = "Taurus"

% Test 5: Late December (Capricorn - year boundary)
z5 = zodiac_sign(12, 25)
% Expected: z5 = "Capricorn"

(k) Leap Year Checker.

Write a function named is_leap_year that determines whether a given year is a leap year.
The rules for leap years are:
For example: 2000 is a leap year (divisible by 400), 1900 is not (divisible by 100 but not 400), 2004 is a leap year (divisible by 4 but not 100).
Inputs:
year (1x1) double β€” the year to check
Outputs:
is_leap (1x1) logical β€” true if the year is a leap year, false otherwise
Test cases:
% Test 1: Divisible by 400 (leap year)
r1 = is_leap_year(2000)
% Expected: r1 = 1 (true)

% Test 2: Divisible by 100 but not 400 (not a leap year)
r2 = is_leap_year(1900)
% Expected: r2 = 0 (false)

% Test 3: Divisible by 4 but not 100 (leap year)
r3 = is_leap_year(2024)
% Expected: r3 = 1 (true)

% Test 4: Not divisible by 4 (not a leap year)
r4 = is_leap_year(2023)
% Expected: r4 = 0 (false)

% Test 5: Another divisible by 100 case
r5 = is_leap_year(2100)
% Expected: r5 = 0 (false)

(l) Quadratic Equation Solver.

Write a function named quadratic_solver that takes the coefficients a, b, and c as inputs and returns the two solutions, x1 and x2 (if they exist), for a quadratic equation of the form
\begin{equation*} ax^2 + bx + c = 0\text{.} \end{equation*}
The function should handle different combinations of a, b, and c being zero. Based on this there could be:
Put on your math hat and think through the different cases to determine how to compute the solutions and what to return when there are no solutions or infinitely many solutions.
Inputs:
a (1x1) double β€” coefficient of \(x^2\)
b (1x1) double β€” coefficient of \(x\)
c (1x1) double β€” constant term
Outputs:
x1 (1x1) double β€” first solution of the quadratic equation
x2 (1x1) double β€” second solution of the quadratic equation
message (1x1) string β€” message indicating the nature of the solutions
message (1x1) string β€” message indicating the nature of the solutions
Test cases:
% Test 1: Two Real Solutions
[x1, x2] = quadratic_solver(1, -3, 2)
% Expected: x1 = 2, x2 = 1

% Test 2: Repeated Solutions
[x1, x2] = quadratic_solver(1, 2, 1)
% Expected: x1 = -1, x2 = -1

% Test 3: Complex Solutions
[x1, x2] = quadratic_solver(1, 0, 4)
% Expected: x1 = 2i, x2 = -2i

(m) Coordinate Quadrant Checker.

Write a function named find_quadrant that determines which quadrant or axis a point (x, y) is located in on a 2D coordinate system.
Rules:
Inputs:
x (1x1) double β€” x-coordinate
y (1x1) double β€” y-coordinate
Outputs:
location (1x1) string β€” "Quadrant I", "Quadrant II", "Quadrant III", "Quadrant IV", "Origin", "X-axis", or "Y-axis"
Test cases:
% Test 1: Quadrant I
loc1 = find_quadrant(3, 4)
% Expected: loc1 = "Quadrant I"

% Test 2: Quadrant II
loc2 = find_quadrant(-2, 5)
% Expected: loc2 = "Quadrant II"

% Test 3: Origin
loc3 = find_quadrant(0, 0)
% Expected: loc3 = "Origin"

% Test 4: X-axis
loc4 = find_quadrant(7, 0)
% Expected: loc4 = "X-axis"

% Test 5: Quadrant III
loc5 = find_quadrant(-3, -8)
% Expected: loc5 = "Quadrant III"

(n) Valid Triangle Detector.

Write a function named is_valid_triangle that determines whether three side lengths form a valid triangle.
A triangle is valid if the sum of the two shortest sides is greater than the longest side and all sides are positive.
Inputs:
a, b, c (1x1) double β€” side lengths of the triangle
Outputs:
is_valid (1x1) logical β€” true if sides form a valid triangle, false otherwise
Test cases:
% Test 1: Equilateral triangle
v1 = is_valid_triangle(5, 5, 5)
% Expected: v1 = 1 (true)

% Test 2: Isosceles triangle
v2 = is_valid_triangle(5, 5, 8)
% Expected: v2 = 1 (true)

% Test 3: Scalene triangle
v3 = is_valid_triangle(3, 4, 5)
% Expected: v3 = 1 (true)

% Test 4: Invalid triangle
v4 = is_valid_triangle(1, 2, 10)
% Expected: v4 = 0 (false)

% Test 5: Another isosceles case
v5 = is_valid_triangle(7, 10, 7)
% Expected: v5 = 1 (true)

(o) Triangle Type Classifier.

Write a function named classify_triangle that classifies a triangle as equilateral, isosceles, scalene, or invalid based on the lengths of its sides.
Rules:
You must use the is_valid_triangle function you wrote in the previous exercise as a β€œhelper” function. This means that your classify_triangle function should (i) contain a call to is_valid_triangle and (ii) have a copy of the is_valid_triangle function code below it in the same file.
Inputs:
a, b, c (1x1) double β€” side lengths of the triangle
Outputs:
type (1x1) string β€” "Equilateral", "Isosceles", "Scalene", or "Invalid"
Test cases:
% Test 1: Equilateral triangle
t1 = classify_triangle(5, 5, 5)
% Expected: t1 = "Equilateral"

% Test 2: Isosceles triangle
t2 = classify_triangle(5, 5, 8)
% Expected: t2 = "Isosceles"

% Test 3: Scalene triangle
t3 = classify_triangle(3, 4, 5)
% Expected: t3 = "Scalene"

% Test 4: Invalid triangle
t4 = classify_triangle(1, 2, 10)
% Expected: t4 = "Invalid"

% Test 5: Another isosceles case
t5 = classify_triangle(7, 10, 7)
% Expected: t5 = "Isosceles"

3. Looping Flow (for and while loops).

(a)

Write a script that computes \(1^2 + 2^2 + \cdots + n^2\) for a given positive integer \(n\text{.}\) Your script should store the result in a variable named S.

(b)

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.

(c)

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.

(d)

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.
You have attempted of activities on this page.