The process where a function calls itself, either directly or indirectly, is known as recursion, and the corresponding function is called a recursive function.
The algorithmic steps for implementing recursion in a function are as follows:
Step1 - Define a base case: Identify the simplest case for which the solution is known or trivial. This is the stopping condition for the recursion, as it prevents the function from infinitely calling itself.
Step2 - Define a recursive case: Define the problem in terms of smaller subproblems. Break the problem down into smaller versions of itself, and call the function recursively to solve each subproblem.
Step3 - Ensure the recursion terminates: Make sure that the recursive function eventually reaches the base case, and does not enter an infinite loop.
step4 - Combine the solutions: Combine the solutions of the subproblems to solve the original problem.
A Mathematical Interpretation
To add the numbers starting from 1 to n. So the function simply looks like this,There is a simple difference between the approach (1) and approach(2) and that is in approach(2) the function “ f( ) ” itself is being called inside the function, so this phenomenon is named recursion
In the above example, the base case for n < = 1 is defined and the larger value of a number can be solved by converting to a smaller one till the base case is reached.
The idea is to represent a problem in terms of one or more smaller problems, and add one or more base conditions that stop the recursion. For example, we compute factorial n if we know the factorial of (n-1). The base case for factorial would be n = 0. We return 1 when n = 0.
Why Stack Overflow error occurs in recursion?
If the base case is not reached or not defined, then the stack overflow problem may arise.
Mathematical Equation:
n if n == 0, n == 1; fib(n) = fib(n-1) + fib(n-2) otherwise;
Recurrence Relation:
T(n) = T(n-1) + T(n-2) + O(1)
Recursive program:
Input: n = 5 Output:
Fibonacci series of 5 numbers is : 0 1 1 2 3
119 docs|30 tests
|
1. What is recursion in computer science? |
2. What are the properties of recursion? |
3. How is recursion implemented in programming languages? |
4. What is the time complexity of recursive algorithms? |
5. What is the space complexity of recursive algorithms? |
|
Explore Courses for Computer Science Engineering (CSE) exam
|