To find the factorial of a number in C#, you can use either a loop or recursion.
Using a loop:
main.cs
int num = 5; // the number whose factorial needs to be foundint factorial = 1;
for (int i = 1; i <= num; i++)
{
factorial *= i;
}
Console.WriteLine("Factorial of " + num + " is " + factorial);
200 chars
10 lines
Using recursion:
main.cs
publicstaticintFactorial(int num){
if (num == 0)
{
return1;
}
else {
return num * Factorial(num - 1);
}
}
// calling the methodint num = 5;
int factorial = Factorial(num);
Console.WriteLine("Factorial of " + num + " is " + factorial);