Recursion
Recursion
Recursion is a technique in Data Structures and Algorithms (DSA) where a function calls itself in
order to solve a problem. It breaks down a problem into smaller sub-problems of the same type until a
base case (termination condition) is met.
In C++, recursion is implemented by writing a function that calls itself directly or indirectly.
int factorial(int n) {
// Base case
if (n == 0 || n == 1) {
return 1;
}
// Recursive case
return n * factorial(n - 1);
}
int main() {
int num;
cout << "Enter a number to calculate its factorial: ";
cin >> num;
cout << "Factorial of " << num << " is " << factorial(num) << endl;
return 0;
}
Output:
Enter a number to calculate its factorial: 5
Factorial of 5 is 120
int fibonacci(int n) {
// Base case
if (n == 0) {
return 0;
}
if (n == 1) {
return 1;
}
// Recursive case
return fibonacci(n - 1) + fibonacci(n - 2);
}
int main() {
int terms;
cout << "Enter the number of terms in the Fibonacci series: ";
cin >> terms;
return 0;
}
Output:
Enter the number of terms in the Fibonacci series: 7
Fibonacci series: 0 1 1 2 3 5 8
Advantages of Recursion:
1. Simpler Code:
• Complex problems can often be expressed more clearly and elegantly using recursion.
• Example: Tree traversals, Tower of Hanoi, and Divide-and-Conquer algorithms.
2. Breaks Down the Problem:
• Recursion helps break down a problem into smaller, easier-to-solve sub-problems.
Disadvantages of Recursion:
1. Higher Memory Usage:
• Each recursive call consumes stack space, which can lead to stack overflow for very
deep recursions.
2. Overhead:
• Function calls involve overhead, making recursion slower than iteration for some
problems.
3. Inefficiency:
• For problems like Fibonacci, naive recursion results in redundant calculations. (Can be
solved using memoization or dynamic programming).
Recursion is a powerful tool in DSA, but it should be used carefully, especially for problems involving
deep recursion or large datasets.
----------------------------------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------------
Here are some practical and commonly asked recursion questions in DSA for C++ that could appear
in exams. Each of these problems tests your understanding of recursion and its practical
implementation.
1. Factorial of a Number
Problem: Write a recursive function to calculate the factorial of a number nn.
Example:
• Input: n = 5
• Output: 120 (5! = 5 × 4 × 3 × 2 × 1)
2. Fibonacci Series
Problem: Write a recursive function to generate the nnth Fibonacci number or the first nn terms of the
Fibonacci series.
Example:
• Input: n = 7
• Output: 0, 1, 1, 2, 3, 5, 8
3. Sum of Digits
Problem: Write a recursive function to calculate the sum of the digits of a given number.
Example:
• Input: n = 1234
• Output: 10 (1 + 2 + 3 + 4)
4. Reverse a String
Problem: Write a recursive function to reverse a given string.
Example:
• Input: str = "hello"
• Output: olleh
5. Tower of Hanoi
Problem: Solve the Tower of Hanoi problem using recursion for nn disks. Print the sequence of moves.
Example:
• Input: n = 3
• Output:
Move disk 1 from A to C
Move disk 2 from A to B
Move disk 1 from C to B
Move disk 3 from A to C
Move disk 1 from B to A
Move disk 2 from B to C
Move disk 1 from A to C
Example:
• Input: str = "radar"
• Output: Yes, it is a palindrome.
Example:
• Input: a = 56, b = 98
• Output: 14
Example:
• Input: str = "abc"
• Output: { "", "a", "b", "c", "ab", "ac", "bc", "abc" }
Example:
• Input: arr = {10, 20, 30, 40, 50}, target = 30
• Output: Found at index 2
Example:
• Input: str = "abc"
• Output:
abc
acb
bac
bca
cab
cba
Example:
• Input: n = 5
• Output: 15 (1 + 2 + 3 + 4 + 5)
Example:
• Input: n = 4
• Output: 5 (Ways: {1+1+1+1, 1+1+2, 1+2+1, 2+1+1, 2+2})
Example:
• Input: n = 5
• Output: 1 2 3 4 5
Example:
• Input: arr = {10, 20, 5, 40, 25}
• Output: 40
1. Factorial of a Number
#include <iostream>
using namespace std;
int factorial(int n) {
if (n == 0 || n == 1) return 1; // Base case
return n * factorial(n - 1); // Recursive case
}
int main() {
int n;
cout << "Enter a number: ";
cin >> n;
cout << "Factorial of " << n << " is " << factorial(n) << endl;
return 0;
}
2. Fibonacci Series
#include <iostream>
using namespace std;
int fibonacci(int n) {
if (n == 0) return 0; // Base case
if (n == 1) return 1; // Base case
return fibonacci(n - 1) + fibonacci(n - 2); // Recursive case
}
int main() {
int n;
cout << "Enter the number of terms: ";
cin >> n;
for (int i = 0; i < n; i++) {
cout << fibonacci(i) << " ";
}
cout << endl;
return 0;
}
3. Sum of Digits
#include <iostream>
using namespace std;
int sumOfDigits(int n) {
if (n == 0) return 0; // Base case
return n % 10 + sumOfDigits(n / 10); // Recursive case
}
int main() {
int n;
cout << "Enter a number: ";
cin >> n;
cout << "Sum of digits: " << sumOfDigits(n) << endl;
return 0;
}
4. Reverse a String
#include <iostream>
using namespace std;
int main() {
string str;
cout << "Enter a string: ";
cin >> str;
reverseString(str, 0);
cout << "Reversed string: " << str << endl;
return 0;
}
5. Tower of Hanoi
#include <iostream>
using namespace std;
int main() {
int n;
cout << "Enter the number of disks: ";
cin >> n;
towerOfHanoi(n, 'A', 'C', 'B');
return 0;
}
int main() {
string str;
cout << "Enter a string: ";
cin >> str;
if (isPalindrome(str, 0, str.length() - 1)) {
cout << "Yes, it is a palindrome." << endl;
} else {
cout << "No, it is not a palindrome." << endl;
}
return 0;
}
int main() {
int a, b;
cout << "Enter the base and exponent: ";
cin >> a >> b;
cout << a << "^" << b << " = " << power(a, b) << endl;
return 0;
}
int main() {
int a, b;
cout << "Enter two numbers: ";
cin >> a >> b;
cout << "GCD of " << a << " and " << b << " is " << gcd(a, b) << endl;
return 0;
}
int main() {
string str;
cout << "Enter a string: ";
cin >> str;
printSubsets(str, "", 0);
return 0;
}
int main() {
int n, target;
cout << "Enter the number of elements: ";
cin >> n;
int arr[n];
cout << "Enter elements in sorted order: ";
for (int i = 0; i < n; i++) cin >> arr[i];
cout << "Enter the target element: ";
cin >> target;
int result = binarySearch(arr, 0, n - 1, target);
if (result != -1) cout << "Element found at index " << result << endl;
else cout << "Element not found." << endl;
return 0;
}
int main() {
string str;
cout << "Enter a string: ";
cin >> str;
printPermutations(str, 0, str.length() - 1);
return 0;
}
int main() {
int n;
cout << "Enter a number: ";
cin >> n;
cout << "Sum of first " << n << " natural numbers is " << sumOfNatural(n) <<
endl;
return 0;
}
int countWays(int n) {
if (n == 0) return 1; // Base case
if (n < 0) return 0; // Invalid case
return countWays(n - 1) + countWays(n - 2); // Recursive case
}
int main() {
int n;
cout << "Enter the number of stairs: ";
cin >> n;
cout << "Number of ways to climb " << n << " stairs: " << countWays(n) << endl;
return 0;
}
void printNumbers(int n) {
if (n == 0) return; // Base case
printNumbers(n - 1); // Recursive case
cout << n << " ";
}
int main() {
int n;
cout << "Enter a number: ";
cin >> n;
printNumbers(n);
cout << endl;
return 0;
}
15. Find the Maximum Element in an Array
#include <iostream>
using namespace std;
int main() {
int n;
cout << "Enter the number of elements: ";
cin >> n;
int arr[n];
cout << "Enter the elements: ";
for (int i = 0; i < n; i++) cin >> arr[i];
cout << "Maximum element is " << findMax(arr, n, 0) << endl;
return 0;
}