In this post we learn How to Write a C# program to find a factorial of a number.
What is Factorial Number?
A factorial number is multiplication of all the smaller and equal numbers of N. where N is a positive number in other words Factorial of n is the product of all positive descending integers.Factorial is a very important concept in the area of mathematics in algebra or in mathematics analytics. It is denoted by sign of exclamation (!) Therefore Factorial of n will be denoted by n! .
Example:
4! = 4 * (4-1) *(4-2) * (4-3)
So
4! = 4*3*2*1 = 24
5! = 5*4*3*2*1 = 120
General Algorithm for Finding Factorial
This is the algorithm to find a factorial of any number. You can use any type of loop in repeat step like for loop, while loop or do-while loop it is totally up to you.
- Start
- Declare Variable n, fact, i
- Read number from User
- Initialize Variable fact=1 and i=1
- Repeat Until i<=number
-
- fact=fact*i
- i=i+1
- Print fact
- Stop
Factorial of predefined number in C#
Here in this program we define a variable a as int data type and initialised it’s value 5 then we find it’s Factorial by below program. I am using for loop in these examples same you can try these by using while and do-while loops.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Factorial { class Program { static void Main() { int a = 5; int fact = 1; for (int x = 1; x <= a; x++) { fact *= x; } Console.WriteLine("factorial is " + fact); Console.ReadLine(); } } }
Output:
C# program to find the Factorial of user input number.
With this program we can find factorial of any number at runtime by giving user input with the help of int.parse method of console.readline(). We have declared a variable n and taking its value by int.parse method.
using System; namespace CSharpProgram { class Program { static void Main(string[] args) { int i, fact = 1, n; Console.Write("Enter number to find the factorial: "); n = int.Parse(Console.ReadLine()); for (i = 1; i <= n; i++) { fact = fact * i; } Console.Write("Factorial of " + n + " is: " + fact); Console.ReadLine(); } } }
Output:
Find Factorial of a number using recursive function in C#
In this program, a recursive function is used for calculating the factorial of a number.
using System; namespace LogicalPrograms { class Program { static void Main(string[] args) { Console.Write("Enter a Number : "); int number = int.Parse(Console.ReadLine()); long factorial = RecursiveFactorial(number); Console.Write($"Factorial of {number} is: {factorial}"); Console.ReadLine(); } static long RecursiveFactorial(int number) { if (number == 1) { return 1; } else { return number * RecursiveFactorial(number - 1); }
Output:
So in this way we can simply find the Factorial of any number in C#.