DEFINING RECURSION
When a function is called within the same function, it is known as recursion in C++. The function which calls the same function is known as a recursive function. Recursion is very useful concept as it empowers a function to solve problems by breaking them down into smaller instances of the same problem.
The figure below shows how recursion works by calling itself over and over again.
BASE CONDITION
The base condition is the condition that is used to terminate the recursion. The recursive function will keep calling itself till the base condition is satisfied.
NOTE
The recursion continues until some condition is met.
To prevent infinite recursion, if...else statement (or similar approach) can be used where one branch makes the recursive call and the other doesn't.
EXAMPLE OF RECURSION PROGRAM
// Factorial of n = 1*2*3*...*n
include
using namespace std;
int factorial(int);
int main() {
int n, result;
cout << "Enter a non-negative number: ";
cin >> n;
result = factorial(n);
cout << "Factorial of " << n << " = " << result;
return 0;
}
int factorial(int n) {
if (n > 1) {
return n * factorial(n - 1);
} else {
return 1;
}
}
OUTPUT:- Enter a non-negative number: 4
Factorial of 4 = 24
EXPLANATION:-
Advantages of C++ Recursion
- It makes our code shorter and cleaner.
- Recursion is required in problems concerning data structures and advanced algorithms, such as Graph and Tree Traversal.
Disadvantages of C++ Recursion
- It takes a lot of stack space compared to an iterative program.
- It uses more processor time.
- It can be more difficult to debug compared to an equivalent iterative program.
Top comments (1)
🌅👌