Support us on YouTube by Subscribing our YouTube Channel. Click here to Subscribe our YouTube Channel

Wednesday 9 September 2020

Program to find factorial of a number in C#

In this blog, we are going to learn How to find factorial of a positive number or integer in C#. As we know that we can find the factorial of a number in multiple ways, out of which I am going to share two ways i.e. with and without the use of recursion.

Program to find factorial of a number without using recursion:
In mathematics, factorial is the product of all positive numbers or integers less than or equal to the number.
Program:

int number, factorial;

Console.WriteLine("Enter a number to calculate its Factorial");

//Recieve input from user

number = int.Parse(Console.ReadLine());

//set factorial value as we will start loop from number-1

factorial = number;

//Multiply the factorial value till i becomes 1

for (int i=number-1;i>=1;i--) {

    factorial = factorial * i;

}

//Display the output to the user

Console.WriteLine("Factorial of " + number + " is: " + factorial);

//Console.ReadLine() to hold the screen after the execution of the program

Console.ReadLine();

Output:

Program to find the factorial of a number with the use of recursion:
A recursive function is a function that calls itself inside the function.
Program:

class Program

{

    //CalculateFactorial method

    public int CalculateFactorial(int number)

    {

        //If number becomes it will return 1 and recursion will stop

        if (number == 1)

        {

            return 1;

        }

        else

        {

            //Calling CalculateFactorial method (Recursion)

            return number * CalculateFactorial(number - 1);

        }

    }

   

    static void Main(string[] args)

    {

        int number;

        Console.WriteLine("Enter a number to calculate its Factorial");

        //Recieve input from user

        number = int.Parse(Console.ReadLine());

        if (number > 0)

        {

            Program objProgram = new Program();

            //Calling CalculateFactorial method

            int factorial = objProgram.CalculateFactorial(number);

            //Display the output to the user

            Console.WriteLine("Factorial of " + number + " is: " + factorial);

        }

        else

        {

            Console.WriteLine("Number must be greater than zero");

        }

        //Console.ReadLine() to hold the screen after the execution of the program

        Console.ReadLine();

    }

}

Output:

I hope this blog will help you in cracking your interview/exam.
Thanks. 


0 comments:

Post a Comment

Subscribe us on YouTube

Subscribe Now

Popular Posts

Contact us

Name

Email *

Message *

Like us on Facebook

Blog Archive