Compute factorial of 5 using a loop and print the result (120).
Ready — edit the code above and click Run.
using System;
class Program
{
static void Main()
{
int n = 5;
long fact = 1;
for (int i = 1; i <= n; i++)
fact *= i;
Console.WriteLine(fact);
}
}
Try solving on your own first, then reveal the official answer.
Iterative factorial avoids stack overflow for larger n. Use long for bigger values.