Grupo
Estructuras de Datos: Pilas y Colas en C++
Ojetivo
1. Implementar una pila para almacenar valores intermedios mientras se calcula el factorial.
2. Introducir cada número desde la entrada hasta 1 en la pila.
3. Extraer los valores de la pila para calcular el factorial.
4. Mostrar el resultado del factorial después de procesar todos los valores.
Crear una pila para calcular el factorial de un número.
Ejemplo de Código C++
Mostrar Código C++
#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
}
Salida
Enter a number to calculate its factorial: 5
The factorial of 5 is 120.
Comparte este ejercicio C++