Saturday, June 10, 2017

C# - Factorial of a given number

In this article, we will calculate the factorial of a given number using C#

What is meant by factorial of a number?

The product of an integer and all the integers below it; e.g. factorial four ( 4! ) is equal to 24.

class Program
    {
        static void Main(string[] args)
        {

            #region Factorial

            Console.WriteLine("Factorial of :");
            int numm = int.Parse(Console.ReadLine());
            Console.WriteLine(PrintFactorial(numm));
            Console.ReadKey();

            #endregion

        }
#region Factorial

        private static double PrintFactorial(int num)
        {
            double fact = 1;

            #region using For Loop

            for (int i = num; i >= 1; i--)
            {
                fact = fact * i;
            }

            #endregion

            #region using While Loop

            while (num > 0)
            {
                fact = fact * num;
                num--;
            }

            #endregion

            return fact;
        }

        #endregion



}
Console Output:

Factorial of :
4
24

No comments:

Post a Comment

SQL INTERVIEW QUESTIONS (SCENARIO BASED) - Part 1

FINDING Second Highest Salary in SQL CREATE TABLE #EMP ( NAME NVARCHAR ( 100 ), SALARY BIGINT ) INSERT INTO #EMP VALUES (...