settingsAccountsettings
By using our mini forum, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy
Menusettings

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

+5 votes

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.

asked in C# category by user matthew44

3 Answers

+2 votes

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#

answered by user sam
edited by user golearnweb
+3 votes

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

answered by user Jolie Ann
edited by user golearnweb
+2 votes

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

answered by user sam
edited by user golearnweb
...