Sunday, 17 August 2025

Write a program to find the factorial of a given integer number using stack.

Write a program to find the factorial of a given integer number using stack.

factorial_stack.c
#include <stdio.h>
#define MAX 100

int stack[MAX];
int top = -1;

// Function to push an element
void push(int val) {
    if(top == MAX - 1) {
        printf("Stack Overflow\n");
    } else {
        stack[++top] = val;
    }
}

// Function to pop an element
int pop() {
    if(top == -1) {
        printf("Stack Underflow\n");
        return -1;
    } else {
        return stack[top--];
    }
}

int main() {
    int n, i;
    long long fact = 1;

    printf("Enter a positive integer: ");
    scanf("%d", &n);

    if(n < 0) {
        printf("Factorial is not defined for negative numbers.\n");
        return 0;
    }

    // Step 1: Push all numbers from n to 1
    for(i = n; i >= 1; i--) {
        push(i);
    }

    // Step 2: Pop all numbers and multiply
    while(top != -1) {
        fact *= pop();
    }

    printf("Factorial of %d is %lld\n", n, fact);

    return 0;
}

✅ Step-by-Step Explanation

🔹 1. Input Validation

if(n < 0) {
    printf("Factorial is not defined for negative numbers.\n");
    return 0;
}
  • Checks for negative input immediately
  • Exits program if input is invalid

🔹 2. Push Numbers to Stack

for(i = n; i >= 1; i--) {
    push(i);
}
  • Pushes numbers from n down to 1 onto the stack
  • Example: n=5 → stack becomes [5,4,3,2,1]

🔹 3. Pop and Multiply

while(top != -1) {
    fact *= pop();
}
  • Pops each number and multiplies with the running product
  • LIFO property ensures correct multiplication order
  • Example: 1 × 2 × 3 × 4 × 5 = 120

🔹 4. Result Output

  • Prints the final factorial result
  • Uses %lld format specifier for long long to handle large numbers

🖨️ Example Runs

Example 1:

Enter a positive integer: 5
Factorial of 5 is 120

Example 2:

Enter a positive integer: 7
Factorial of 7 is 5040

📌 Key Concepts Covered

Stack Operations
Implementation of push/pop functions with error checking
LIFO Principle
Last-In-First-Out behavior used for multiplication order
Factorial Algorithm
n! = n × (n-1) × ... × 1 implemented using stack
Input Validation
Handling edge case for negative numbers
Data Types
Using long long to handle large factorial results

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