2080 4

BIT102 ยท 2080 ยท 5 marks

What is recursion? Write a program to find the factorial of a given integer using recursion.

What is recursion? Write a program to find the factorial of a given integer using recursion. [5]

C ProgrammingChapter 7: Functions and RecursionFactorial using recursion

Quick answer

Recursion is a programming technique where a function calls itself directly or indirectly to solve a problem. A recursive function solves a problem by breaking it down into smaller subproblems of the same type until it reaches a base case (a condition where the function stops calling itself).

Recursion and Factorial Program

What is Recursion?

Every recursive function must have:

  1. Base Case - the condition that terminates the recursion
  2. Recursive Case - the part where the function calls itself

Factorial Using Recursion

Mathematical Definition

$$n! = \begin{cases} 1 & \text{if } n = 0 \text{ or } n = 1 \ n \times (n-1)! & \text{if } n > 1 \end{cases}$$

Example: 5! = 5 ร— 4 ร— 3 ร— 2 ร— 1 = 120


C Program

#include <stdio.h>

// Recursive function to calculate factorial
int factorial(int n) {
    // Base case
    if (n == 0 || n == 1) {
        return 1;
    }
    // Recursive case
    else {
        return n * factorial(n - 1);
    }
}

int main() {
    int num;
    printf("Enter a positive integer: ");
    scanf("%d", &num);

    if (num < 0) {
        printf("Factorial is not defined for negative numbers.\n");
    } else {
        printf("Factorial of %d = %d\n", num, factorial(num));
    }
    return 0;
}

Trace of Execution (for n = 5)

factorial(5)
  = 5 * factorial(4)
        = 4 * factorial(3)
              = 3 * factorial(2)
                    = 2 * factorial(1)
                              = 1       <-- Base case
                    = 2 * 1 = 2
              = 3 * 2 = 6
        = 4 * 6 = 24
  = 5 * 24 = 120

Output:

Enter a positive integer: 5
Factorial of 5 = 120

Key Points

AspectDescription
Base Casen == 0 or n == 1, returns 1
Recursive Casen * factorial(n-1)
Stack UsageEach call is pushed onto the call stack
TerminationRecursion stops when base case is reached

Short on time? The 1, 5 and 10 mark versions of this answer, flashcards and practice sets come with a program pass.