Recursion
What is Recursion?
A function calls itself is called recursion. Recursion is a useful technique. it is shorter and easier to write.
Example:
Factorial problems using Recursion.
Java
- int fact(int n){
- if(n==1)
- return 1;
- else if(n==0)
- return 1;
- else return n*fact(n-1)
- }
- fact(5)
Python
- def fact(n):
- if n==0:
- return 1
- return n*fact(n-1)
- print(fact(5))
Explanation:
5*fact(5-1) 5*return value 24= 120 final result
4*fact(4-1) 4*return value 6 = 24
3*fact(3-1) 3*return value 2 = 6
2*fact(2-1) 2*return value 1 = 2
1*fact(1-1) return 1
Each recursive call makes a new copy of that method in memory. Memory removed for that method once it return.
Comments
Post a Comment