Thursday, 31 July 2025

Write a program to find out the factorial of a number using recursion (stack).

Write a program to find out the factorial of a number using recursion (stack).

factorial_recursion.c
#include <stdio.h>

// Function to calculate factorial using recursion
int factorial(int n) {
    if (n == 0 || n == 1)
        return 1;
    else
        return n * factorial(n - 1);
}

int main() {
    int num;
    printf("Enter a number to find its factorial: ");
    scanf("%d", &num);

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

    return 0;
}

🪜 Step-by-Step Explanation

🔹 Step 1: Input from User

printf("Enter a number to find its factorial: ");
scanf("%d", &num);
  • Takes an integer input from the user (e.g., num = 5)
  • Uses scanf() to read the input value
  • Stores the value in variable num

🔹 Step 2: Factorial Function Definition

int factorial(int n) {
    if (n == 0 || n == 1)
        return 1;
    else
        return n * factorial(n - 1);
}

This is a recursive function with:

  • Base case: If n is 0 or 1, return 1 (stopping condition)
  • Recursive case: Returns n multiplied by factorial(n - 1)
  • Each call reduces the problem size until reaching the base case

🔹 Step 3: Understanding Stack Behavior (Recursion)

Each recursive call is pushed onto the call stack:

factorial(5)
    => 5 * factorial(4)
        => 4 * factorial(3)
            => 3 * factorial(2)
                => 2 * factorial(1)
                    => 1 (base case returns 1)

Then the stack unwinds with results:

factorial(1) = 1
factorial(2) = 2 * 1 = 2
factorial(3) = 3 * 2 = 6
factorial(4) = 4 * 6 = 24
factorial(5) = 5 * 24 = 120

🖨️ Sample Output

Input:

Enter a number to find its factorial: 5

Output:

Factorial of 5 is: 120

📌 Key Concepts Covered

Recursion
Function calling itself with reduced input size
Base Case
Condition that stops recursion when n == 0 || n == 1
Call Stack
Each function call is stored in stack memory until it returns
Factorial Definition
n! = n × (n-1) × (n-2) × ... × 1
Validation
Handles case for negative input (factorial undefined)

No comments:

Post a Comment

Total Pageviews

Search This Blog

Write a program which performs the following operations using a simple queue. : insert() -> delete() -> display()

Write a program which performs the following operations using a simple queue. : insert() -> delete() -> display() ...