C++ Recursion

πŸ” C++ Recursion

Recursion is a technique where a function calls itself to solve a problem by breaking it into smaller subproblems.
Every recursive function must have:

  1. Base case – stops recursion

  2. Recursive case – calls itself with a smaller input


πŸ”Ή 1. Basic Syntax

return_type functionName(parameters) {
if (base_condition)
return value; // base case

return functionName(smaller_problem); // recursive call
}


πŸ”Ή 2. Simple Example (Print Numbers)

void print(int n) {
if (n == 0)
return;

cout << n << " ";
print(n - 1);
}

int main() {
print(5);
}

Output:

5 4 3 2 1

πŸ”Ή 3. Factorial Using Recursion

int factorial(int n) {
if (n == 1)
return 1;

return n * factorial(n - 1);
}

int main() {
cout << factorial(5);
}

Output:

120

πŸ”Ή 4. Fibonacci Series (Recursive)

int fib(int n) {
if (n <= 1)
return n;

return fib(n - 1) + fib(n - 2);
}

int main() {
cout << fib(6);
}

Output:

8

πŸ”Ή 5. Sum of Digits Using Recursion

int sumDigits(int n) {
if (n == 0)
return 0;

return (n % 10) + sumDigits(n / 10);
}

int main() {
cout << sumDigits(1234);
}

Output:

10

πŸ”Ή 6. Reverse a Number (Recursive)

void reverse(int n) {
if (n == 0)
return;

cout << n % 10;
reverse(n / 10);
}


πŸ”Ή 7. Recursion vs Loop

Recursion Loop
Function calls itself Repeats using iteration
Uses stack memory Uses less memory
Cleaner for problems like trees Faster for simple repetition
Risk of stack overflow No stack overflow

πŸ”Ή 8. Common Mistakes ❌

❌ Missing Base Case

void fun() {
fun(); // infinite recursion
}

➑ Causes stack overflow


❌ Wrong Base Condition

if (n < 0) return 1; // incorrect logic

πŸ”Ή 9. Tail Recursion

Recursive call is the last statement.

void print(int n) {
if (n == 0)
return;

cout << n << " ";
print(n - 1);
}

βœ” Easier to optimize
βœ” Similar to loops


πŸ”Ή 10. When to Use Recursion

  • Tree and graph traversal

  • Divide and conquer algorithms

  • Problems with repetitive structure

  • Mathematical definitions (factorial, Fibonacci)


πŸ“Œ Summary

  • Recursion = function calling itself

  • Must have a base case

  • Solves problems by reducing size

  • Elegant but uses more memory

  • Avoid deep recursion if possible

You may also like...