Sunday, September 8, 2024
HomeC#Program to search out factorial of a quantity in C# ~ IT...

# Program to search out factorial of a quantity in C# ~ IT Tutorials with Instance

On this weblog, we’re going to be taught How one can discover factorial of a optimistic quantity or integer in C#. As we all know that we are able to discover the factorial of a quantity in a number of methods, out of which I’m going to share two methods i.e. with and with out the usage of recursion.

Program to search out factorial of a quantity with out utilizing recursion:

In arithmetic, factorial is the product of all optimistic numbers or integers lower than or equal to the quantity.

Program:

 int quantity, factorial; Console.WriteLine(“Enter a quantity to calculate its Factorial”); //Recieve enter from person quantity = int.Parse(Console.ReadLine()); //set factorial worth as we are going to begin loop from number-1 factorial = quantity; //Multiply the factorial worth until i turns into 1 for (int i=number-1;i>=1;i–) {     factorial = factorial * i; } //Show the output to the person Console.WriteLine(“Factorial of “ + quantity + ” is: “ + factorial); //Console.ReadLine() to carry the display after the execution of this system Console.ReadLine();

Output:

Program to search out the factorial of a quantity with the usage of recursion:

A recursive perform is a perform that calls itself contained in the perform.

Program:

 class Program {     //CalculateFactorial methodology     public int CalculateFactorial(int quantity)     {         //If quantity turns into it should return 1 and recursion will cease         if (quantity == 1)         {             return 1;         }         else         {             //Calling CalculateFactorial methodology (Recursion)             return quantity * CalculateFactorial(quantity – 1);         }     }         static void Predominant(string[] args)     {         int quantity;         Console.WriteLine(“Enter a quantity to calculate its Factorial”);         //Recieve enter from person         quantity = int.Parse(Console.ReadLine());         if (quantity > 0)         {             Program objProgram = new Program();             //Calling CalculateFactorial methodology             int factorial = objProgram.CalculateFactorial(quantity);             //Show the output to the person             Console.WriteLine(“Factorial of “ + quantity + ” is: “ + factorial);         }         else         {             Console.WriteLine(“Quantity should be higher than zero”);         }         //Console.ReadLine() to carry the display after the execution of this system         Console.ReadLine();     } }

Output:

I hope this weblog will enable you to in cracking your interview/examination.

Thanks.

RELATED ARTICLES