![]() |
What is an example of using recursive functions? |
[Edit] |
Answer
Let's take the example of finding the factorial of a number (of a positive integer).
The factorial of N is N * (N-1) * (N-2) * (N-3) ... * 3 * 2 *1
It is the product of all integers between that number (including that number) and 1.
For example, factorial 2 = 2*1 = 2 factorial 3 = 3*2*1 = 6 factorial 4 = 4*3*2*1= 24
Now you define a recursive function Fac (N) as Fac (N) = Fac (N-1) * N, with Fac(1) predefined as 1. Thus, Fac(N-1) = Fac(N-2) * (N-1) and Fac(N-2) = Fac(N-3) * (N-2) and thus recursion takes over until such time fac(1) needs to be evaluated. We know the value of Fac(1) which is set as 1.
Thus we can evaluate Factorial(N) using recursion.
First answer by Vbala 99. Last edit by Vbala 99. Contributor trust: 536 [recommend contributor]. Question popularity: 37 [recommend question]




