Grupo
Funciones en C++
Ojetivo
1. Cree una función llamada factorial que tome un entero como entrada.
2. Use una sentencia if para definir el caso base: si el número es 0, devuelva 1.
3. Para el caso recursivo, devuelva n multiplicado por el factorial de n - 1.
4. En la función principal, solicite al usuario que ingrese un número.
5. Llame a la función recursiva y muestre el resultado.
Implemente una función recursiva para calcular el factorial de un número.
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
// Recursive function to calculate the factorial of a number
int factorial(int n) {
if (n == 0) {
return 1; // Base case: factorial of 0 is 1
}
return n * factorial(n - 1); // Recursive call
}
// Main function
int main() {
int number;
// Ask the user to enter a number
cout << "Enter a non-negative integer: ";
cin >> number;
// Check if the number is negative
if (number < 0) {
cout << "Factorial is not defined for negative numbers." << endl;
} else {
// Call the recursive factorial function and print the result
int result = factorial(number);
cout << "Factorial of " << number << " is: " << result << endl;
}
return 0; // End of the program
}
Salida
Enter a non-negative integer: 5
Factorial of 5 is: 120
Comparte este ejercicio C++