Factorial program in C# with example and logic. l
For Example to find the factorial of a number 6 is 720.
(6!=6*5*4*3*2*1=720)
How to find factorial?
The factorial of a number denoted as n!.
Factorial Formula.
n!=n*(n-1)*(n-2)*…*1
For suppose to find the factorial of a number 6 as based on above formula.
6!=6*(6-1)*(6-2)*(6-3)*(6-4)*(6-5)
=6*5*4*3*2*1
=720
Notes:
- The factorial number is product of number in its descending order.
- Factorial of 0 is 0!=1
- No factorial for Negative Number.
Example of factorial program in C# using for loop
using System;
/*
C# example for finding factorial of a number using for loop
*/
class Program
{
static void Main(string[] args)
{
//initialized number by 6
int number = 6;
//initialized factorial by 1
int factorial=1;
for (int j = number; j >= 1; j--)
{
factorial = factorial * j;
}
Console.WriteLine("the factorial of the number " + number + " =" + factorial);
}
}
}
Output
the factorial of the number 6 = 720
Example of factorial program in C# using while loop
/*
C# example for finding factorial of a number using while loop
*/
class Program
{
static void Main(string[] args)
{
//initialized number by 6
int number = 6;
//initialized factorial by 1
int factorial=1;
int j = number;
while (j >= 1)
{
factorial = factorial * j;
j = j - 1;
}
Console.WriteLine("the factorial of the number " + number + " =" + factorial);
}
}
Example of factorial program in C# using do-while loop
class Program
{
static void Main(string[] args)
{
//initialized number by 6
int number = 6;
//initialized factorial by 1
int factorial=1;
int j = number;
do
{
factorial = factorial * j;
j = j - 1;
} while (j >= 1);
Console.WriteLine("the factorial of the number " + number + " =" + factorial);
}
}
Example of factorial program in C# using function
class Program
{
static void Main(string[] args)
{
//initialized number by 6
int number = 6;
//initialized factorial by 1
int factorial=1;
Program p = new Program();
//call the function by passing value to find the factorial
factorial = p.fact(number);
Console.WriteLine("the factorial of the number " + number + " =" + factorial);
}
public int fact(int number)
{
int factorial = 1;
int j = number;
while (j >= 1)
{
factorial = factorial * j;
j = j - 1;
}
return factorial;
}
}
Example of factorial program in C# using Recursive function
class Program
{
static void Main(string[] args)
{
//initialized number by 6
int number = 6;
//initialized factorial by 1
int factorial=1;
Program p = new Program();
factorial = p.fact(number);
Console.WriteLine("the factorial of the number " + number + " =" + factorial);
}
public int fact(int number)
{
if (number==0 || number==1)
{
return 1;
}
else
{
return number * fact(number - 1);
}
}
}