This Java Factorial Example shows how to finds factorial of a given number using Java. Entered number is checked first if its negative then an error message is printed.
Factorial Program in Java: Factorial of n non-negative integer denoted by n! is multiplying all the integers from n to 1. The factorial can be obtained using a recursive method.
factorial of n (n!) = n * (n-1) * (n-2) * (n-3).....
0! = 1
5! = 5*4*3*2*1 = 120
6! = 6*5*4*3*2*1 = 720
In mathematics, the factorial is used in Permutations and Combinations.
The factorial notation is represented by an exclamation mark “!”. For example, you will see it as 5! or 6!. You read it as ‘five factorial’ and ‘six factorial.’
We’ll be covering the following topics in this tutorial:
Algorithm for Factorial Number
START
Step 1 → Enter the value of A.
Step 2 → Multiply value, A to 1 descending order.
Step 3 → The final integer value is factorial of A.
STOP
Java Example for the Factorial Program
//Factorial Program in Java
import java.util.Scanner; public class Factorial { public static void main(String[] args) { try { int number ; System.out.println("Enter an integer to Finds it's factorial"); Scanner scan = new Scanner(System.in); number = scan.nextInt(); if ( number < 0 ) System.out.print("Number should be non-negative."); else { int fact = number; for(int i =(number - 1); i > 1; i--) { fact = fact * i; } System.out.println("Factorial of a number is " + fact); } } catch (Exception e){} } }
Output of program: