Wednesday 16 March 2016

Factorial Program in Java

Factorial Program in Java

The factorial of a number is defined is the product of natural numbers from one to that particular number. Mathematically, Here we write Factorial Program in Java.

Factorial Program in Java


n! = 1 * 2 * 3 * .... * (n-1) * n

For example, the factorial of 4 and 5 is

4! = 4*3*2*1 = 24

5! = 5*4*3*2*1 = 120

Here we write factorial program in java

Code:

public class Factorial
{
public static void main(String[] args) 
{
int n = 5;
int fact = 1;
for (int i = 1; i <= n; i++) 
{
fact = fact * i;
}
System.out.println("Factorial of 5 is: " + fact);
}
}

Output:

Factorial of 5 is : 120

No comments:

Post a Comment