Java Program to Find Factorial of a number

JavaObject Oriented ProgrammingProgramming

In this article, we will understand how to find the factorial of a number. Factorial of a number is the product of itself with each of its lower numbers.

Factorial is a function applied to natural numbers greater than zero. The symbol for the factorial function is an exclamation mark after a number, like this: 5!

Below is a demonstration of the same −

Input

Suppose our input is −

Enter the number : 5

Output

The desired output would be the following i.e. 5! = 5x4x3x2x1

The factorial of 5 is 120

Algorithm

Step1- Start
Step 2- Declare three integers: my_input_1, factorial and i
Step 3- Prompt the user to enter an integer value/ Hardcode the integer
Step 4- Read the values
Step 5- Run while loop, multiply the number with its lower number and run the loop till the
number is reduced to 1.
Step 6- Display the result
Step 7- Stop

Example 1

Here, the input is being entered by the user based on a prompt. You can try this example live in ourcoding ground tool run button.

import java.util.Scanner;
public class FindFactorial{
   public static void main(String arg[]){
      int my_input, factorial, i;
      System.out.println("Required packages have been imported");
      Scanner my_scanner = new Scanner(System.in);
      System.out.println("A scanner object has been defined ");
      System.out.println("Enter a number: ");
      my_input = my_scanner.nextInt();
      factorial=1;
      for(i=1;i<=my_input;i++){
         factorial=factorial*i;
      }
      System.out.printf("The factoral of %d is %d" , my_input,factorial);
   }
}

Output

Required packages have been imported
A scanner object has been defined
Enter a number:
5
The factorial of 5 is 120

Example 2

Here, the integer has been previously defined, and its value is accessed and displayed on the console

public class FindFactorial{
   public static void main(String arg[]){
      int my_input, factorial, i;
      my_input = 5;
      System.out.printf("The number is %d ",my_input );
      factorial=1;
      for(i=1;i<=my_input;i++){
         factorial=factorial*i;
      }
      System.out.printf("\nThe factorial of %d is %d" , my_input,factorial);
   }
}

Output

The number is 5
The factorial of 5 is 120
raja
Updated on 21-Feb-2022 10:10:43

Advertisements