C++ Recursion

Recursion is a powerful concept in programming that involves calling a function from within itself. In C++, recursion can be used to solve problems that are naturally recursive in nature, such as factorial calculation, Fibonacci series, and tree traversal.

A recursive function must have a base case, also known as the stopping condition, which terminates the recursion. If the base case is not met, the function calls itself with a modified set of inputs until the base case is met and the recursion terminates.

Example: Factorial Calculation

1#include <iostream> 2using namespace std; 3 4int factorial(int num) 5{ 6 if (num == 0) 7 return 1; 8 9 return num * factorial(num - 1); 10} 11 12int main() 13{ 14 int num; 15 16 cout << "Enter a positive integer: "; 17 cin >> num; 18 19 cout << "Factorial of " << num << " is " << factorial(num) << endl; 20 21 return 0; 22}


1Enter a positive integer: 5 2Factorial of 5 is 120

It is important to note that recursion can have a large impact on the performance of your code, as each recursive call results in the creation of a new stack frame. Therefore, it is essential to use recursion carefully and make sure that the base case is well defined and will always be reached.