Java Programs

Factorial Program in Java using for loop Iterative method

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 ( 12345 = 120).
Case2: If the user input the 6.
then the output should be 720 (12345*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

  1. The factorial of 0 is 1
  2. The factorial of any negative number is not defined.
  3. The factorial only exits for whole numbers

Our logic to calculate Factorial of number using for loop

  1. Our program will create three variables i, num, factorial of long types
  2. Our program will take an integer input from the user which should be a whole number.
  3. If the number input is negative then print ‘The factorial can’t be calculated’.
  4. Then use for loop to calculate the factorial.
  5. 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 5: if(number<0):
print ‘cannot be calculated.
Else if ( number == 0):
print 1
else: for (i=1; i<=num, i++)
factorial = factorial*i
Step 6: print factorial
Step 7: Stop

Program:

import java.util.*;

public class Main {
    
	public static void main(String[] args) {
    long i, num, factorial=1;
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter a number to calculate factorial: ");
    num = sc.nextInt();
    
    if(num < 0) {
        System.out.println("Factorial can't be calculated for negative number");
    } else if (num == 0) {
       System.out.println("Factorial of 0 is 1");
    } else {
        for(i=1;i<=num;i++)
          factorial=factorial*i;
        System.out.println("Factorial = "+factorial);
     }
    
    }
}

Output 1:

Enter a number to calculate factorial: 
5
Factorial = 120

Explanation

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

Output 2

Enter a number to calculate factorial: 
8
Factorial = 40320

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

About the Author: Elavarasan PK

Technical Specialist, Intersoft Data Labs