Recursion
Recursion
Recursive functions
A recursive function is one which makes a new call to itself partway through, passing a new value as
a parameter
It is a form of iteration
When the function recurses it begins again with a new parameter or set of parameters
The current state of the registers and variables are added to the stack
This continues until a Base case is met one which can be determined immediately and doesn’t
require another function call to get a result
All recursive functions must have a base case or exit clause or which causes the recursion to end and
return a value; this is usually the state where a result can be returned without having to do
something else first
Recursive solutions are often shorter but have a larger space complexity each recursive call adds a
new set of data (frame) to the stack and creates multiple instances of each variable
Return num1
Endif
Endfunction
Num1
else
num1=num2
num2 = temp
calculate(5) is called.
calculate(1) returns 1
calculate(2) returns 2 + 1 = 3
calculate(3) returns 3 + 3 = 6
calculate(4) returns 4 + 6 = 10
calculate(5) returns 5 + 10 = 15