MVC ASP.NET C# SQL Server WCF Written Test HR Round Subscribe C# Videos C# Programs Buy DVD

C# Program to compute factorial of a number

In mathematics, 5 factorial is computed as 5X4X3X2X1, which is equal to 120. 5 factorial is denoted as 5 and an exclamation mark as shown below.
5 Factorial = 5! = 5X4X3X2X1 = 120 
4 Factorial = 4! = 4X3X2X1 = 24
3 Factorial = 3! = 3X2X1 = 6

Factorial of Zero is 1.

C# Program below shows how to compute factorial for a given number. If you like this artcile, please click g+1 button below to share with your friends.



using System;
namespace SamplePrograms
{
    class Factorial
    {
        public static void Main()
        {
            // Prompt the user to enter their target number to calculate factorial
            Console.WriteLine("Please enter the number for which you want to compute factorial");


            try
            {
                // Read the input from console and convert to integer data type
                int iTargetNumber = Convert.ToInt32(Console.ReadLine());


                // Factorial of Zero is 1
                if (iTargetNumber == 0)
                {
                    Console.WriteLine("Factorial of Zero = 1");
                }
                // Compute factorial only for non negative numbers
                else if (iTargetNumber < 0)
                {
                    Console.WriteLine("Please enter a positive number greater than 1");
                }
                // If the number is non zero and non negative
                else
                {
                    // Declare a variable to hold the factorial result.
                    double dFactorialResult = 1;


                    // Use for loop to calcualte factorial of the target number
                    for (int i = iTargetNumber; i >= 1; i--)
                    {
                        dFactorialResult = dFactorialResult * i;
                    }


                    // Output the result to the console
                    Console.WriteLine("Factorial of {0} = {1}", iTargetNumber, dFactorialResult);
                }
            }
            catch (FormatException)
            {
                // We get format exception if user enters a word instead of number
                Console.WriteLine("Please enter a valid number", Int32.MaxValue);
            }
            catch (OverflowException)
            {
                // We get overflow exception if user enters a very big number, 
                // which a variable of type Int32 cannot hold
                Console.WriteLine("Please enter a number between 1 and {0}", Int32.MaxValue);
            }
            catch (Exception)
            {
                // Any other unforeseen error
                Console.WriteLine("There is a problem! Please try later");
            }
        }
    }
}


No comments:

Post a Comment