August 25, 2022

Java Program to Find Factorial

In this post we’ll see a Java program to find the factorial of a number.

Factorial of a non-negative integer n is product of all positive integers less than or equal to n. For example

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

Factorial program in Java

Factorial program in Java can be written as both iterative as well as recursive solution. In this post both of the solutions are given.

Factorial program using iteration

In the following program user is asked to enter the number for which factorial has to be calculated. In iterative logic you can start a for loop with the entered number and decrease it by 1 in each iteration. What you need is the multiplication of all the numbers in the loop.

import java.util.Scanner;

public class Factorial {
  public static void main(String[] args) {
    // Input from user
    Scanner input = new Scanner(System.in);
    System.out.println("Enter a number: ");
    int number = input.nextInt();
    int factorial = 1;
    for(int i = number; i >= 1; i--){
      factorial = factorial * i; 
    }
    System.out.println("Factorial of " + number + " is " + factorial); 
  }
}
Output
Enter a number: 
5
Factorial of 5 is 120

Factorial program in Java using recursion

In the recursive logic to write factorial Java program, you need to call the same method recursively passing the (number – 1) as parameter every time until the base case (number = 1) is reached.

import java.util.Scanner;

public class Factorial {
  public static void main(String[] args) {
    // Input from user
    Scanner input = new Scanner(System.in);
    System.out.println("Enter a number: ");
    int number = input.nextInt();
    int factorial = calculateFactorial(number);

    System.out.println("Factorial of " + number + " is " + factorial); 
  }
	
  // Factorial using recursion
  private static int calculateFactorial(int num){
    // base case
    if(num == 1){
      return 1;
    }else{
      return num * calculateFactorial(num - 1);
    }
  }
}
Output
Enter a number: 
8
Factorial of 8 is 40320

That's all for the topic Java Program to Find Factorial. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment