Write a program to find the factorial of a given integer number using stack.
✅ 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 forlong 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