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.
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:
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:
0 comments:
Post a Comment