Recursive functions are functions that calls itself. It is always made up of 2 portions, the base case and the recursive case.
Let's use recursive functions to find the factorial of an integer. A factorial is the product of all integers from 1 to the number itself.
In the example below, we will be looking for the factorial of 4, or, 4!.
Factorial of 4 is 4! = 1 * 2 * 3 * 4 = 24
Now let's analyse what is going on in the above recursive function.
return(x * factorial(x-1))
which will give us return(4 * factorial(3))
.factorial(3)
which will give us return(3 * factorial(2))
and it goes on until we have x == 1
(the base case) and then the recursion will terminate. This means that if we do not have a base case to stop the recursion, the function will continue to call itself indefinitely.return(4 * 3 * 2 * 1)
Visualize how the codes work by clicking on the Next button below.
Write a recursive function that will sum all numbers from 1 to n.
n is the argument of the function.
Write a recursive function that will find the smallest number in a list.
Let the list be A = [1, 4, 24, 17, -5, 10, -22]
HINT:
Use the min
function in python