How to calculate the factorial of a number?
Previous | Home | Next |
In this java program we calculate the factorial of a number.
To calculate the factorial of a number we use a formula n!
For example if we want to calculate the factorial of 2 as 2*1 i.e 2
Here we take two variables int number and int fact
first assign value 7 to the variable number
and then assign number to the variable fact.
set a loop till the value of i become equal to (number -1)
and the pass the value of fact*1 to the fact.
public class FactNumber {
public static void main(String[] args) {
int number = 7;
int fact = number;
for(int i =(number - 1); i > 1; i--)
{
fact = fact* i;
}
System.out.println("Factorial of a number is " + fact);
}
}
The factorial of a number is 5040.
Previous | Home | Next |