How can recursion be implemented effectively in PHP to solve mathematical problems like compound interest calculations?
To implement recursion effectively in PHP for solving mathematical problems like compound interest calculations, we can create a recursive function that calculates the compound interest for each period until reaching the desired number of periods. The function should call itself with updated parameters until the base case is met.
function compoundInterest($principal, $rate, $periods) {
if ($periods == 0) {
return $principal;
} else {
$compoundInterest = $principal * $rate;
return compoundInterest($principal + $compoundInterest, $rate, $periods - 1);
}
}
$principal = 1000;
$rate = 0.05;
$periods = 5;
echo "Compound interest after $periods periods: $" . compoundInterest($principal, $rate, $periods);
Related Questions
- How can the use of session variables in PHP impact the security and functionality of a script?
- How can PHP functions like addslashes and stripslashes help mitigate security risks associated with user input?
- How can the use of foreach loops in PHP help in iterating through arrays and performing calculations on the data?