0% found this document useful (0 votes)
14 views14 pages

Recursion

Uploaded by

mcak33358
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views14 pages

Recursion

Uploaded by

mcak33358
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

What is Recursion in DSA?

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.

Key Concepts of Recursion:


1. Base Case:
• The condition that stops the recursive function from continuing indefinitely.
• Without a base case, the recursion will result in an infinite loop (or stack overflow).
2. Recursive Case:
• The part of the function where it calls itself with modified arguments, gradually reducing
the problem size to reach the base case.
3. Call Stack:
• Each recursive call is placed on the call stack.
• When the base case is reached, the calls start returning in reverse order of their
execution.

Example: Factorial Using Recursion


Factorial (n!n!) is the product of all positive integers less than or equal to nn. For example:
5!=5×4×3×2×15! = 5 \times 4 \times 3 \times 2 \times 1
Recursive Formula:
n!=n×(n−1)!and0!=1(base case)n! = n \times (n-1)! \quad \text{and} \quad 0! = 1 \quad (\text{base
case})

C++ Code for Factorial Using Recursion:


#include <iostream>
using namespace std;

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

Example: Fibonacci Series Using Recursion


The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding
ones:
F(0)=0, F(1)=1, F(n)=F(n−1)+F(n−2)for n>1F(0) = 0, \, F(1) = 1, \, F(n) = F(n-1) + F(n-2) \quad \
text{for} \, n > 1

C++ Code for Fibonacci Using Recursion:


#include <iostream>
using namespace std;

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;

cout << "Fibonacci series: ";


for (int i = 0; i < terms; i++) {
cout << fibonacci(i) << " ";
}
cout << endl;

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).

When to Use Recursion in DSA:


• Solving problems that can be divided into smaller sub-problems of the same type.
• Examples:
1. Divide-and-Conquer Algorithms:
• Merge Sort, Quick Sort, Binary Search.
2. Tree Traversals:
• Preorder, Inorder, Postorder.
3. Graph Algorithms:
• Depth First Search (DFS).
4. Dynamic Programming:
• Solving problems with overlapping sub-problems.
Iterative vs. Recursive Approach
Feature Iterative Approach Recursive Approach
Complexity Lower overhead Higher due to function calls
Readability Sometimes less readable Often more readable
Memory Usage Uses less memory Uses stack space
Examples Loops (e.g., for, while) Tree traversals, Divide-and-Conquer

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

6. Check if a String is a Palindrome


Problem: Write a recursive function to check if a given string is a palindrome.

Example:
• Input: str = "radar"
• Output: Yes, it is a palindrome.

7. Find the Power of a Number


Problem: Write a recursive function to calculate aba^b (a raised to the power of b).
Example:
• Input: a = 2, b = 5
• Output: 32 (2⁵ = 32)

8. Greatest Common Divisor (GCD)


Problem: Write a recursive function to calculate the GCD of two numbers using Euclid's algorithm.

Example:
• Input: a = 56, b = 98
• Output: 14

9. Print All Subsets of a String


Problem: Write a recursive function to generate all subsets (power set) of a given string.

Example:
• Input: str = "abc"
• Output: { "", "a", "b", "c", "ab", "ac", "bc", "abc" }

10. Binary Search Using Recursion


Problem: Write a recursive function to implement binary search for a sorted array.

Example:
• Input: arr = {10, 20, 30, 40, 50}, target = 30
• Output: Found at index 2

11. Print All Permutations of a String


Problem: Write a recursive function to print all permutations of a given string.

Example:
• Input: str = "abc"
• Output:
abc
acb
bac
bca
cab
cba

12. Sum of First nn Natural Numbers


Problem: Write a recursive function to calculate the sum of the first nn natural numbers.

Example:
• Input: n = 5
• Output: 15 (1 + 2 + 3 + 4 + 5)

13. Count the Number of Ways to Climb Stairs


Problem: A person can climb 1 or 2 steps at a time. Write a recursive function to find the number of
ways the person can climb nn stairs.

Example:
• Input: n = 4
• Output: 5 (Ways: {1+1+1+1, 1+1+2, 1+2+1, 2+1+1, 2+2})

14. Print Numbers from 1 to nn


Problem: Write a recursive function to print numbers from 1 to nn in increasing order.

Example:
• Input: n = 5
• Output: 1 2 3 4 5

15. Find the Maximum Element in an Array


Problem: Write a recursive function to find the maximum element in an array.

Example:
• Input: arr = {10, 20, 5, 40, 25}
• Output: 40

How to Prepare for Recursion Questions in Exams


1. Understand Base Cases:
• Every recursive function must have a base case to stop recursion.
2. Break Down Problems:
• Divide the problem into smaller sub-problems and solve them recursively.
3. Trace the Function Calls:
• Practice tracing recursive function calls to understand the flow of execution.
4. Optimize with Dynamic Programming:
• Learn to avoid redundant calculations in problems like Fibonacci or climbing stairs
using memoization.
5. Practice Common Patterns:
• Recursion for arrays, strings, trees, and mathematical problems are common topics in
exams.
Let me know if you'd like a detailed solution for any of these questions! 😊
Here are the solutions for all the questions you asked, with only #include <iostream> and
using namespace std included:

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;

void reverseString(string &str, int i) {


if (i >= str.length() / 2) return; // Base case
swap(str[i], str[str.length() - i - 1]); // Swap characters
reverseString(str, i + 1); // Recursive case
}

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;

void towerOfHanoi(int n, char source, char target, char auxiliary) {


if (n == 1) {
cout << "Move disk 1 from " << source << " to " << target << endl;
return;
}
towerOfHanoi(n - 1, source, auxiliary, target);
cout << "Move disk " << n << " from " << source << " to " << target << endl;
towerOfHanoi(n - 1, auxiliary, target, source);
}

int main() {
int n;
cout << "Enter the number of disks: ";
cin >> n;
towerOfHanoi(n, 'A', 'C', 'B');
return 0;
}

6. Check if a String is a Palindrome


#include <iostream>
using namespace std;

bool isPalindrome(string &str, int left, int right) {


if (left >= right) return true; // Base case
if (str[left] != str[right]) return false;
return isPalindrome(str, left + 1, right - 1); // Recursive case
}

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;
}

7. Find the Power of a Number


#include <iostream>
using namespace std;

int power(int a, int b) {


if (b == 0) return 1; // Base case
return a * power(a, b - 1); // Recursive case
}

int main() {
int a, b;
cout << "Enter the base and exponent: ";
cin >> a >> b;
cout << a << "^" << b << " = " << power(a, b) << endl;
return 0;
}

8. Greatest Common Divisor (GCD)


#include <iostream>
using namespace std;

int gcd(int a, int b) {


if (b == 0) return a; // Base case
return gcd(b, a % b); // Recursive case
}

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;
}

9. Print All Subsets of a String


#include <iostream>
using namespace std;

void printSubsets(string str, string current, int index) {


if (index == str.length()) {
cout << current << endl;
return;
}
printSubsets(str, current, index + 1); // Exclude the character
printSubsets(str, current + str[index], index + 1); // Include the character
}

int main() {
string str;
cout << "Enter a string: ";
cin >> str;
printSubsets(str, "", 0);
return 0;
}

10. Binary Search Using Recursion


#include <iostream>
using namespace std;
int binarySearch(int arr[], int left, int right, int target) {
if (left > right) return -1; // Base case
int mid = left + (right - left) / 2;
if (arr[mid] == target) return mid;
if (arr[mid] > target) return binarySearch(arr, left, mid - 1, target);
return binarySearch(arr, mid + 1, right, target);
}

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;
}

11. Print All Permutations of a String


#include <iostream>
using namespace std;

void printPermutations(string str, int left, int right) {


if (left == right) {
cout << str << endl;
return;
}
for (int i = left; i <= right; i++) {
swap(str[left], str[i]); // Swap
printPermutations(str, left + 1, right); // Recur
swap(str[left], str[i]); // Backtrack
}
}

int main() {
string str;
cout << "Enter a string: ";
cin >> str;
printPermutations(str, 0, str.length() - 1);
return 0;
}

12. Sum of First nn Natural Numbers


#include <iostream>
using namespace std;
int sumOfNatural(int n) {
if (n == 0) return 0; // Base case
return n + sumOfNatural(n - 1); // Recursive case
}

int main() {
int n;
cout << "Enter a number: ";
cin >> n;
cout << "Sum of first " << n << " natural numbers is " << sumOfNatural(n) <<
endl;
return 0;
}

13. Count the Number of Ways to Climb Stairs


#include <iostream>
using namespace std;

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;
}

14. Print Numbers from 1 to nn


#include <iostream>
using namespace std;

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 findMax(int arr[], int n, int index) {


if (index == n - 1) return arr[index]; // Base case
return max(arr[index], findMax(arr, n, index + 1)); // Recursive case
}

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;
}

Let me know if you need any further clarifications! 😊

You might also like