How To: Factorial Program In C# .Net

What is a factorial?

A factorial is the result of an integer multiplied by all the integers less than it. For example if you want to know the factorial of 3 then it can be calculated as 3*2*1 = 6. So factorial of 3 is 6. Similarly factorial of 5 is 5*4*3*2*1 = 120. 

Note that factorial is always calculated for non-negative integers. So there is nothing like negative factorials. 

In Algebra an exclamatory symbol (!) is used as a factorial notation.
So if we want to calculate factorial of 5 then we can write it as below:
5! = 120. 

So how to find factorial of a number like 0? Answer is, factorial of 0 is always 1.


What is a factorial Number?

A number whose factorial is being calculated is a factorial number. In  the below example, 6 is a factorial number.

6! = 720


Factorial of a number in C#

Programming languages like Java, C, C++ etc. can be used to write programs that can calculate factorial of a number. In this post we will use the C# programming language to calculate the factorials. To write or understand a factorial program in C# you should be familiar with this programming language. If you are not then I will strongly suggest you to go through my C# tutorial series created specifically for the beginners.

In this post I will give examples using the below methods to calculate the factorial of a number:
  1. Factorial program in C# using For Loop
  2. Factorial program in C# using While Loop 
  3. Factorial program in C# using recursion 
To write a factorial calculator program in C# we will create a console application using Visual Studio 2010. You can use any version of Visual studio as these programs will run on all of them.

1. Factorial program in C# using For Loop

In the below example the user is asked to enter a number. Using int.TryParse function it is checked if the number entered is a valid integer or not.

The GetFactorial() is a C# factorial function that checks if the number is 0 or 1. Since factorial of 0 and 1 is always 1 hence 1 is returned immediately without doing any further calculation.

The For Loop is written in such a manner that it multiplies the numbers in a descending order.


using System;

namespace FactorialCalculator{
    class Program
    {
        static void Main(string[] args)
        {
            int number;
            Console.WriteLine("Enter a positive number:");
            bool isNumber = int.TryParse(Console.ReadLine(), out number);

            if (number > 0)
            {
                Console.WriteLine("Factorial of {0} is {1}", number, GetFactorial(number));
                Console.ReadLine();
            }
        }

        static int GetFactorial(int number)
        {
            if (number == 0 || number == 1)
            {
                return 1;
            }
            int result = number;
            for (int count = number; count > 1; count--)
            {
                result = result * (count - 1);
            }

            return result;
        }
    }
}

Below is the output of the above factorial program using For Loop:

Enter a number:
9
Factorial of 9 is 362880

2. Factorial program in C# using While Loop 

Let's now calculate the factorial using While Loop. In the below program the same logic is used as before but instead of For Loop a While Loop is used.

Note that the example factorial C# code below decrements the value of variable count inside the loop. This helps in creating a descending order of numbers.

using System;

namespace FactorialBlog{
    class Program
    {
        static void Main(string[] args)
        {
             int number;
            Console.WriteLine("Enter a positive number:");
            bool isNumber = int.TryParse(Console.ReadLine(), out number);

            if (number > 0)
            {
                Console.WriteLine("Factorial of {0} is {1}", number, GetFactorial(number));
                Console.ReadLine();
            }
        }

        static int GetFactorial(int number)
        {
            if (number == 0 || number == 1)
            {
                return 1;
            }
            int result = number;
            int count = number;

            while (count > 1)
            {
                result = result * (count - 1);
                count--;
            }
            return result;
        }
    }
}

Below is the output of the above factorial program using While Loop:

Enter a number:
5
Factorial of 5 is 120

3. Factorial program in C# using Recursion

Till now we have used loops (For Loop and While Loop) to get factorial of a number. Let's now write a program to find factorial using recursion. For those who don't know what recursion is - Recursion is a process where a function calls itself to implement a logic. 

Just a word of caution, be careful when you use a recursive logic, especially when the logic is complicated. Recursion may increase the complexity of the logic even more and you may find it very difficult to debug the program. Sometimes recursion may also lead to infinite loops so you should take care of this aspect as well when writing such a program.

using System;

namespace FactorialBlog
{
    class Program
    {
        static void Main(string[] args)
        {
            int number;

            Console.WriteLine("Enter a positive number:");
            bool isNumber = int.TryParse(Console.ReadLine(), out number);

            if (number > 0)
            {
                Console.WriteLine("Factorial of {0} is {1}", number, GetFactorial(number));
                Console.ReadLine();
            }
        }

        static int GetFactorial(int number)
        {
            if (number == 0)
            {
                return 1;
            }

            if (number > 1)
                number = number * GetFactorial(number - 1);

            return number;            
        }
    }

}

Below is the output of the above factorial program using recursion:

Enter a number:
6
Factorial of 6 is 720

Conclusion

In this post I discussed about the basics a factorial number and how you can calculate factorial of a number in different ways in C#. I showed you how you can do this by using For Loop, While Loop and Recursion. 

If you liked this post then kindly Share it, Like it or +1 it.



1 comment:

  1. factorial hundred In the last few days, the “factorial of 100” is one of the top subjects and a lot of maths geeks compute it using voice assistants such as Alexa, Shiri, etc.

    ReplyDelete