Recursion
The process in which function calls itself directly or indirectly is called recursion and the corresponding function is called as recursive function.
We use recursion to solve bigger problem into smaller problems. One thing we have to keep in mind, that if such sub-problem is following same kind of patterns, then only we can use the recursive approach.
A recursive function has two different parts. The base case and the recursive case.
The base case is used to terminate the task of recurring. If base case is not defined then the function will recur infinite number of times.
Recursive case simplifies a bigger problem into number of simpler sub-problems and then calls them.
The following image shows the working of a recursive function called recurse.
Example
Factorial of a number is the product of all the integers from 1 to that number. For example the factorial of 6 (denoted as 6!) is :
1*2*3*4*5*6=720
def foctorial(x):
"This is a recursive function to find the factorial"
if (x==1):
return 1
else:
return(x*factorial(x-1))
num=6
print("The factorial of", num, "is",factorial(num))
Output
The factorial of 6 is 720
In the above example, factorial() is a recursive function as it calls itself.
No comments:
Post a Comment