Calculate the Factorial of a Number Using a Stack in C++

In this C++ exercise, you will implement a program that calculates the factorial of a given number using a stack. A stack is a Last In, First Out (LIFO) data structure that can be used to store and manage intermediate results while calculating the factorial. The program will simulate the process of calculating the factorial by pushing intermediate values onto the stack and then popping them off to compute the final result. This exercise helps reinforce the use of stacks in C++ and understanding the factorial concept.

Group

Data Structures: Stacks, Queues in C++

Objective

1. Implement a stack to store intermediate values while calculating the factorial.
2. Push each number from the input down to 1 onto the stack.
3. Pop the values off the stack to calculate the factorial.
4. Display the factorial result after all values have been processed.

Create a stack to calculate the factorial of a number.

Example C++ Exercise

 Copy C++ Code
#include <iostream>  // Include for input/output operations
#include <stack>      // Include for stack operations

using namespace std;

// Function to calculate factorial using a stack
int calculateFactorial(int n) {
    stack<int> numStack;  // Declare a stack to store numbers for factorial calculation
    int factorial = 1;  // Initialize the factorial variable
    
    // Push all numbers from n down to 1 onto the stack
    for (int i = n; i > 1; i--) {
        numStack.push(i);  // Push the current number onto the stack
    }

    // Pop numbers off the stack and multiply to calculate the factorial
    while (!numStack.empty()) {
        factorial *= numStack.top();  // Multiply the top element of the stack with factorial
        numStack.pop();  // Pop the element from the stack
    }

    return factorial;  // Return the calculated factorial
}

// Main function to execute the program
int main() {
    int number;
    cout << "Enter a number to calculate its factorial: ";
    cin << number;  // Input the number from the user

    int result = calculateFactorial(number);  // Calculate the factorial using the stack
    cout << "The factorial of " << number << " is " << result << "." << endl;

    return 0;  // End of the program
}

 Output

Enter a number to calculate its factorial: 5
The factorial of 5 is 120.

Share this C++ Exercise


More C++ Programming Exercises of Data Structures: Stacks, Queues in C++

Explore our set of C++ Programming Exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of C++. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in C++.