Three ways to find Factorial of a Number in C#

In this article three ways are given by which you can Find factorial of a number. This question is quite simple and done mostly with the help of recursion. Obviously this is not the only way to do, other ways are also there to do this, So here Three of them are represented. Take a look

1. Using For Loop:
2. Using Recursion:
3. Using While loop:

[eg. Factorial of 5 = 5*4*3*2*1]

Factorial

1. Using For Loop

using System;

class Program
{
    static void Main(string[] args)
    {
        int num, fact=1;
        Console.Write("\n Enter a Number : ");
        num = Convert.ToInt32(Console.ReadLine());

        for (int i = 1; i <= num; i++)
        {
            fact = fact * i;  // Or fact *= i
        }

        Console.WriteLine(" Factorial of Given Number : " + fact);
        Console.ReadKey();
    }
}

2. Using Recursion

using System;

class Program
{
    static void Main(string[] args)
    {
        int num, fact;

        Console.Write("\n Enter a Number : ");
        num = Convert.ToInt32(Console.ReadLine());

        fact = Find_Factorial(num); // Recursion

        Console.WriteLine(" Factorial of Given Number : " + fact);
        Console.ReadKey();
    }
    private static int Find_Factorial(int num)
    {
        if (num == 1)
            return 1;
        else
        {
            int fac = num * Find_Factorial(num - 1);
            return fac;
        }
    }
}




3. Using While Loop

using System;

class Program
{
    static void Main(string[] args)
    {
        int num, fact=1;

        Console.Write("\n Enter a Number : ");
        num = Convert.ToInt32(Console.ReadLine());
        while (num != 1)
        {
            fact = fact * num; //  fact *= num;
            num = num - 1;    // num -= 1;
        }
        
        Console.WriteLine(" Factorial of Given Number : " + fact);
        Console.ReadKey();
    }
}