MCS-011 Problem Solving and Programming

First year, Semester 1

Chapters

Newsletter

Recursion

Recursion refers to the process where a function calls itself directly or indirectly to solve a problem. It is a powerful tool in programming that allows for elegant solutions to problems that can be broken down into simpler, repetitive tasks. However, it must be used with caution to avoid issues like infinite loops or excessive memory usage.

Key Concepts of Recursion

  1. Base Case: This is the condition under which the recursion terminates. Without a base case, the recursion would continue indefinitely.
  2. Recursive Case: This is the part of the function where the function calls itself with modified arguments, progressively working towards the base case.


Here’s a C program to calculate the factorial of a number using recursion:

#include
// Function to calculate factorial using recursion int factorial(int n) { if (n == 0) { return 1; // Base case: 0! is 1 } else { return n * factorial(n - 1); // Recursive case } } int main() { int number; printf("Enter a positive integer: "); scanf("%d", &number); if (number < 0) { printf("Factorial is not defined for negative numbers.\n"); } else { int result = factorial(number); printf("Factorial of %d is %d\n", number, result); } return 0; }


Explanation

  1. Base Case: The base case is if (n == 0), which returns 1. This stops the recursion when n reaches 0.
  2. Recursive Case: The recursive step is n * factorial(n - 1), which calls the function with n - 1 and multiplies the result by n.


Output

Enter a positive integer: 5 Factorial of 5 is 120


Advantages

  1. Recursion can make the code simpler and more elegant, especially for problems that have a natural recursive structure (e.g., tree traversals, factorials, Fibonacci sequence).
  2. For some problems, recursive solutions can be more intuitive and easier to understand than iterative solutions.


Disadvantages

  1. Recursive calls can add overhead due to the multiple function calls and increased memory usage for the call stack.
  2. Deep recursion can lead to stack overflow errors if the recursion depth exceeds the stack size limit.
  3. For some problems, recursion can make the code more complex and harder to debug, especially if the base case or the recursive logic is not correctly defined.

Report an issue

Reporting: Recursion (topic)

Related Posts