Grupo
Control de Flujo en C++
Ojetivo
1. Solicitar al usuario que introduzca un entero positivo.
2. Inicializar una variable para almacenar el resultado factorial, comenzando por 1.
3. Usar un bucle para multiplicar el resultado factorial por cada entero de 1 a N.
4. Mostrar el resultado factorial final.
5. Probar el programa con diferentes valores de N.
Calcular el factorial de un número mediante un bucle.
Ejemplo de Código C++
Mostrar Código C++
#include <iostream> // Include the iostream library for input and output
using namespace std; // Use the standard namespace
// Main function - the entry point of the program
int main() {
int N, factorial = 1; // Declare the variable N to store user input and factorial initialized to 1
// Ask the user to enter a positive integer
cout << "Enter a positive integer: ";
cin >> N; // Read the user input and store it in N
// Use a for loop to calculate the factorial of the number
for (int i = 1; i <= N; ++i) {
factorial *= i; // Multiply factorial by each integer from 1 to N
}
// Display the result of the factorial
cout << "The factorial of " << N << " is: " << factorial << endl;
return 0; // Return 0 to indicate that the program executed successfully
}
Salida
Enter a positive integer: 5
The factorial of 5 is: 120
Comparte este ejercicio C++