Java Program to print Factorial of a number

Factorial of a number using java :

 

Factorial of a number is the product of all numbers or integers which are between the range of the number and one. Or can say, factorial of an integer is the product of all the integers below it, till 1.

  • For 0, the factorial is 1 ;
  • For negative numbers, the factorial values are not defined.

 

In this article we will create a program to calculate the factorial of a number. For better understanding let’s consider some examples :

  • 5 : Factorial of 5 is 5 * 4 * 3 * 2 * 1 = 120 ,
  • 7 : Factorial of 7 is 7 * 6 * 5 * 4 * 3 * 2 * 1 = 5040
Factorial of a number using java

Working :

Step 1 : Ask the user to enter a number whose factorial is to be calculated.

Step 2 : Use a condition to check the number entered by the user is greater than and equal to 0 or not, because for negative numbers the factorial values are not defined. If this condition gets true, then move to the Step 3, otherwise move to the Step 7.

Step 3 : Define a variable fac to store the factorial of a number and initialize the variable with value 1.

Step 4 : Use a loop to multiply all numbers which are less than and equal to number entered by the user and greater than and equal to 1 and store the result in variable fac.

Step 5 : Repeat the Step 3 till the result not found.

Step 6 : Display the Result.

Step 7 : Print the message “Value is not defined, please re-enter the value”.

Code in Java :

//Java program to find factorial of a number
import java.util.Scanner;
public class factorial
{
public static void main(String[] args)
{
//scanner class declaration
Scanner sc = new Scanner(System.in);
//input from user
System.out.print("Enter a number : ");
int number = sc.nextInt();
if(number >= 0)
{
//declare a variable to store factorial
int fac = 1;
for(int i = number ; i >= 1 ; i--)
fac = fac * i;
//display the result
System.out.println("Factorial of "+number+" is "+fac);
//closing scanner class(not compulsory, but good practice)
}
else
System.out.println("Value is not defined, please re-enter the value");
sc.close();
}
}

Output :

Enter a number : 4

Factorial of 4 is 24


Enter a number : 0

Factorial of 0 is 1


Enter a number : -1

Value is not defined, please re-enter the value.

Please Login/Signup to comment