Challenge - Functions and loops
Build an interest calculator with parameterized functions, loops and return.
Challenge - Functions and loops
In this challenge you'll write an interest calculator. The computeInterest(float $principal, float $rate, int $years) function computes compound interest with a for loop and returns the balance via return.
Each year the interest is added to the balance; the next year's interest is computed on the grown balance. This combines parameterized functions, loops and arithmetic operators.
for loop refresher
A for loop has three parts: initialization ($i = 0), condition ($i < $years) and increment ($i++). The body runs while the condition is true.
For compound interest you keep the balance in $balance and update it each step with $balance += $balance * ($rate / 100). When the loop ends, return $balance gives the result.
Exercise Write the interest calculator
Define computeInterest(float $principal, float $rate, int $years): float. In the body start with $balance = $principal. Open a for ($i = 0; $i < $years; $i++) loop; in the body write $balance += $balance * ($rate / 100). After the loop return $balance;. Finally add echo computeInterest(1000, 10, 3) . "\n";.
Show example solution
float. Start with $balance = $principal; loop over years with for, update with $balance += $balance * ($rate / 100); return $balance.
Example solution:
<?php
// Write computeInterest with a for loop
function computeInterest(float $principal, float $rate, int $years): float {
$balance = $principal;
for ($i = 0; $i < $years; $i++) {
$balance += $balance * ($rate / 100);
}
return $balance;
}
echo computeInterest(1000, 10, 3) . "\n";
Test yourself
-
What happens each year in compound interest?
- Only the principal grows
- The rate halves
- Principal stays fixed, interest kept separate
- Interest is added to the balance, next interest is computed on it
Show answer
Interest is added to the balance, next interest is computed on it — Correct. Each year interest is added to the balance; the next year's interest is computed on the grown balance.
-
Complete the compound interest update
<?php function computeInterest(float $principal, float $rate, int $years): float { $balance = $principal; for ($i = 0; $i < $years; $i++) { $balance ____= $balance * ($rate / 100); } return $balance; } ?>Show answer
<?php function computeInterest(float $principal, float $rate, int $years): float { $balance = $principal; for ($i = 0; $i < $years; $i++) { $balance +== $balance * ($rate / 100); } return $balance; } ?> -
Match the interest calculator parts
- $principal
- principal
- $rate
- annual rate %
- $years
- year count
- $balance
- current balance