Recursive functions are the functions those call themselves. This recursion occurs until a specified condition is met and the function finally returns a value instead of going for recursion.
Also the number of recursion is limited to the stack size.
A recursion is always aimed to start from one value and end at another value.
A perfect example for recursion is calculating the factorial. Lets consider calculating the factorial of 5.
The Recursive function for the factorial can be defined as :
Also the recursion plays an important role in several other algorithms too such as Binary Search, Quick Sort, etc.. But before you go to the recursion, try to use iteration and from iteration call the function. Also try to analyse and use the alternatives while going to recursion.
Also the number of recursion is limited to the stack size.
A recursion is always aimed to start from one value and end at another value.
A perfect example for recursion is calculating the factorial. Lets consider calculating the factorial of 5.
The Recursive function for the factorial can be defined as :
int factorial(int num) { if(num>0) { return num*factorial(num-1); } else { return 1; } }The recursion takes place as follows : factorial(5) returns 5*factorial(4) factorial(4) returns 4*factorial(3) factorial(3) returns 3*factorial(2) factorial(2) returns 2*factorial(1) factorial(1) returns 1*factorial(0) factorial(0) returns 1 Thus factorial(1) becomes 1*1 = 1 since factorial(0) = 1 factorial(2) becomes 2*1 = 2 since factorial(1) = 1 factorial(3) becomes 3*2 = 6 since factorial(2) = 2 factorial(4) becomes 4*6 = 24 since factorial(3) = 6 factorial(5) becomes 5*24 = 120 since factorial(4) = 24 To put this in much more layman term, factorial(5) = 5 * factorial(4) = 5 * 4 * factorial(3) = 5 * 4 * 3 * factorial(2) = 5 * 4 * 3 * 2 * factorial(1) = 5 * 4 * 3 * 2 * 1 * factorial(0) = 5 * 4 * 3 * 2 * 1 * 1 = 120
Also the recursion plays an important role in several other algorithms too such as Binary Search, Quick Sort, etc.. But before you go to the recursion, try to use iteration and from iteration call the function. Also try to analyse and use the alternatives while going to recursion.
No comments:
Post a Comment