Article

Factorial program in Java

In this article we will learn about Factorial program in Java.

Factorial Program : The factorial of n is denoted by n! and calculated by the integer numbers from 1 to n.

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

Factorial program in Java

Find Factorial of a number using for loop.
[php]

import java.util.Scanner;

class FacorialProgramExample
{
public static void main(String args[])
{
int num,fact=1;
Scanner sc=new Scanner(System.in);
System.out.println("Enter an Integer number:");
//The input provided by user is stored in num
num=sc.nextInt();

for(int i=1;i<=num;i++){
fact=fact*i;

}
System.out.print("Factorial of "+num+" is = " +fact);
}
}
[/php]

Output for Factorial program in Java

factorial-program-in-java

Example 2: Find Factorial of a number using while loop

[php]

import java.util.Scanner;

class FacorialProgramExample
{
public static void main(String args[])
{
int num,fact=1,i=1;
Scanner sc=new Scanner(System.in);
System.out.println("Enter an Integer number:");
//The input provided by user is stored in num
num=sc.nextInt();
while(i <= num)
{
fact=fact*i;
i++;
}
System.out.print("Factorial of "+num+" is = " +fact);
}
}
[/php]

Output

Leave a Reply

Your email address will not be published.