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
Show 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.