Factorial program in C# - Calculate and find the factorial of a number

  

2
Emne starter

Hello, I need to learn how can I find factorial of a particular number in C#?


For instance, "four factorial": "4!" means 1×2×3×4 = 24.

3 Svar
2

THIS IS HOW TO FIND FACTORIAL WITH WHILE LOOP:

using System;
 
class FindFactorialWhileLoop
{
    static void Main()
    {
        {
            Console.Write("Enter your factorial number = ");
            decimal n = decimal.Parse(Console.ReadLine());
            decimal result = 1;
 
            while (true)
            {
                Console.Write(n);
                if (n == 1)
                {
                    break;
                }
                Console.Write(" * ");
                result *= n;
                n--;
            }
            Console.WriteLine(" = {0}", result);
        }
    }
}

while loop in c sharp

1

The best option is to use the for loop:

using System;
 
class FindFactorial
{
    static void Main()
    {
        Console.WriteLine("Please enter your number: ");
        int n = int.Parse(Console.ReadLine());
 
        int factorial = 1;
        for (int i = 1; i <= n; i++)
        {
            factorial *= i;
        }
 
        Console.WriteLine(factorial);
    }
}

for loop in C#

1

Here is with the do-while loop:

using System;
 
class FindFactorialDoWhileLoop
{
    static void Main()
    {
        Console.Write("Please enter your number: ");
        int n = int.Parse(Console.ReadLine());
 
        int factorial = 1;
 
        do
        {
            factorial *= n;
            n--;
        } while (n > 0);
        Console.WriteLine("n! = {0}", factorial);
    }
}

do while loop in C sharp

Del: