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.
You are expected to comply with University policies and guidelines namely, Appropriate Use of Information Resources Policy, IT Usage Policy and Social Media Policy. Users will be personally liable for any infringement of Copyright and Licensing laws. Unless otherwise stated, all guide content is licensed by CC BY-NC 4.0.