Search code examples
c#factorial

C# to calculate factorial


I have this code that gets an input from the user and calculate its factorial and the factorial for less than the input number, but I keep getting the factorial for the first number only and the rest is 0. It should be like this: For example, if the input is 5:

5! = 120

4! = 24

3! = 6

2! = 4

1! = 1

How do I make the loop go throw all the numbers below the input number?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

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

            Console.WriteLine(".....................[Application 1].....................\n\n");
            Console.WriteLine("Please enter a number to get its factorial: ");
            num = Convert.ToInt32(Console.ReadLine());

            n = num; // Assign n to num

            while (num > 0)
            {
                for (int i = n - 1; i > 0; i--)
                {
                   n *= i;
                }
                Console.WriteLine("Factorial of {0}! = {1}\n", num, n);
                num--;
            }
        }
    }
}

Solution

  • Just move n = num; inside the while loop:

    while (num > 0)
    {
        n = num;
        for (int i = n - 1; i > 0; i--)
        {
            n *= i;
        }
        Console.WriteLine("Factorial of {0}! = {1}\n", num, n);
        num--;
    }