In this tutorial, we are going to learn java program to find the factorial of the number given as input from the user using for loop.
Problem Statement
For any Input numbers given by the user, we have to calculate the factorial of that numbers.
For example
Case1: If the user input the 5.
then the output should be 120 ( 1*2*3*4*5 = 120).
Case2: If the user input the 6.
then the output should be 720 (1*2*3*4*5*6 =720).
What is the Factorial of a number?
The factorial of a number is the multiplication of each and every number till the given number except 0.
For example:
Factorial of number 4 is the multiplication of every number till number 4, i.e. 1*2*3*4 = 24
Important Point
• The factorial of 0 is 1
• The factorial of any negative number is not defined.
• The factorial only exits for whole numbers
Our logic to calculate Factorial of number using for loop
• Our program will create three variables i, num, factorial of long types
• Our program will take an integer input from the user which should be a whole number.
• If the number input is negative then print ‘The factorial can’t be calculated’.
• Then use for loop to calculate the factorial.
• After that, we will store the value of the factorial in a variable and finally print the value of the variable.
Algorithm to calculate Factorial of Number
Step 1: Start
Step 2: declare variable i, num, factorial in long data-type
Step 3: initialize variable ‘factorial’ with the value 1.
Step 4: Take an integer input from user to calculate the factorial
Step 4: if(number<0):
print ‘cannot be calculated.
Else if ( number == 0):
print 1
else: for (i=1; i<=num, i++)
factorial=factorial*i
Step 5: print factorial
Step 6: Stop
Java Program to calculate factorial using for loop
Output 1

Explanation
The input number from the user to find the factorial is 5. The calculated value of the factorial is 120.
Output 2

The input number from the user to find the factorial is 8. The calculated value of the factorial is 40320.