Ejercicio
Función factorial (iterativa)
Objetivo
Cree una función iterativa (no recursiva) para calcular el factorial del número especificado como parámetro:
Console.Write ( Factorial (6) );
mostraría
720
Código de Ejemplo
// Importing necessary namespaces
using System;
class Program
{
// Main method to drive the program
public static void Main()
{
// Calling the Factorial function with the number 6
Console.WriteLine(Factorial(6)); // Output will be 720
}
// Iterative function to calculate the factorial of a number
public static int Factorial(int n)
{
// Initialize the result variable to 1 (since factorial of 0 is 1)
int result = 1;
// Iterate through numbers from 1 to n and multiply them together
for (int i = 1; i <= n; i++)
{
result *= i; // Multiply the current result by i
}
// Return the calculated factorial value
return result;
}
}