Recursion
Introduction
Recursion is when a function calls itself to solve a problem.
Most famous example
Above, a base case stops the recursion, and the recursive case keeps it going. To find the factorial of a number, the base case is when the number is 1 (since 1! = 1). The recursive case calls the function with the number minus one. Key elements include the function, the base case, and the recursive call. If the base case isn’t reachable, then we have an infinite loop.
Suit tailoring shop
// Function to calculate the total cost of tailoring suits
// Example usage:
;
;
`Total cost for tailoring suits: $`;
Above, the totalTailoringCost
function calculates the total cost of tailoring a certain number of suits. It uses recursion by breaking down the problem of tailoring multiple suits into smaller parts: tailoring one suit and tailoring the rest. This continues until the base case is reached (no suits requested), at which point the recursion stops.
We work with recursion because it helps us break down certain types problems more manageable, smaller chunks, reducing redundancy and improving readability.
In PHP and Python
# Base case: If no suits are requested, return 0
return 0
# Recursive case: Calculate the cost of tailoring one suit and add it to the cost of tailoring the rest
= 100 # Cost of tailoring one suit
return + # Recursive call with one less suit
# Example usage:
= 5
=
The logic from both flow in the same way. Checkout the resources below for a more expansive approach and explanation.