Tutorial Gateway

  • C
  • C#
  • Java
  • Python
  • SQL
  • MySQL
  • Js
  • BI Tools
    • Informatica
    • Talend
    • Tableau
    • Power BI
    • SSIS
    • SSRS
    • SSAS
    • MDX
    • R Tutorial
    • QlikView
  • More
    • C Programs
    • C++ Programs
    • Python Programs
    • Java Programs
    • SQL FAQ’s

Factorial Program in Java

by suresh

Write a Factorial Program in Java Programming Language using For Loop, While Loop, Functions, and Recursion.

Java Factorial Program using For Loop

This program for factorial allows the user to enter any integer value. By using this value, this Java program finds Factorial of a number using the For Loop.

The Factorial of number is the product of all the numbers less than or equal to that number & greater than 0. It is denoted with a (!) symbol. The mathematical representation of the Factorial is as shown below:

n! = n * (n-1) * (n -2) * …….* 1

For example, five Factorial is represented as 5! = 5 * 4 * 3 * 2 * 1 = 120

// Factorial Program in Java using For Loop
package FrequentPrograms;

import java.util.Scanner;

public class FactorialNumberUsingFor {
	private static Scanner sc;
	public static void main(String[] args) {
		int i, Number; 
		long Factorial = 1;
		sc = new Scanner(System.in);		
		System.out.println(" Please Enter any number to Find Factorial: ");
		Number = sc.nextInt();
		
		for (i = 1; i <= Number; i++)  {
			Factorial = Factorial * i;
		}
		System.out.format("\nFactorial of %d = %d\n", Number, Factorial);
	}
}

OUTPUT

Factorial Program in Java 1

ANALYSIS

In this factorial program in Java, First, We declared two integer variables i and number. We also declared one long variable Factorial and the assigned value of 1.

int i, Number; 
long Factorial = 1;

NOTE: Although we are calculating the factorial of an integer variable, we declared output (Factorial) as a long variable. Because, when we are writing a Java program for calculating the factorial for large integers, the result will cross the integer limit.

The following System.out.println statement will ask the user to enter his/her own integer value to calculate the factorial. Next, we are assigning the user entered value to the Number variable

System.out.println(" Please Enter any number to Find Factorial: ");
Number = sc.nextInt();

Within the For Loop, We initialized the integer I value to 1 and also (i <= Number) condition will help the loop to terminate when the condition fails.

for (i = 1; i <= Number; i++)  {
	Factorial = Factorial * i;
}

Let us see the working principle of this Java factorial program for loop in iteration wise. From the above screenshot, you can observe that the user entered the value: Number = 4 and as we know i = 10 and Factorial = 1.

First Iteration

  • Condition inside the For loop (1 <= 4) is True. So, the program will start executing statements inside the for loop
  • Factorial = Factorial * i;
  • Factorial = 1 *1 = 1
  • Lastly, i will increment to 1. It means i will become 2. Please refer Increment and Decrement Operators article to understand the ++ notation.

Second Iteration

From the first iteration, i became 2 and Factorial = 1

  • Condition inside the For loop (2 <= 4) is True. So, the Java Factorial program will start executing statements inside the for loop
  • Factorial = 1 *2 = 2
  • Lastly, i will increment to 1. It means i will become 3.

Third Iteration

From the second iteration, i = 3 and Factorial = 2

  • For loop Condition (3 <= 4) is True
  • Factorial = Factorial * i;
  • Factorial = 2 *3 = 6
  • Lastly, i will increment to 1. It means i will become 4.

Fourth Iteration

From the third iteration of Java factorial program, i = 4 and Factorial = 6

  • Condition inside the For loop (4 <= 4) is True
  • Factorial = 6 * 4 = 24
  • Lastly, i incremented to 1. It means i will become 5.

Fifth Iteration

Condition inside the For loop (4 <= 4) is False so, For loop will be Terminated.

Last System.out.format statement will print the Factorial output of the user entered integer. Within the statement, the first %d refers to Number, and the second %d refers to Factorial.

System.out.format("\nFactorial of %d = %d\n", Number, Factorial);

Factorial Program in Java using While Loop

This Java factorial program allows the user to enter any integer value. By using this value, this Java factorial program will find Factorial of a number using the While Loop

// Factorial Program in Java using While Loop
package FrequentPrograms;

import java.util.Scanner;

public class FactorialNumberUsingWhile {
	private static Scanner sc;
	public static void main(String[] args) {
		int i = 1, Number; 
		long Factorial = 1;
		sc = new Scanner(System.in);		
		System.out.println(" Please Enter any number to Find Factorial: ");
		Number = sc.nextInt();
		
		while (i <= Number)  {
			Factorial = Factorial * i;
			i++;
		}
		System.out.format(" Factorial of %d = %d", Number, Factorial);
	}
}

We just replaced the For loop in the above Java factorial program example with the While loop. If you do not understand the While Loop, then please refer to Java article here: Java While Loop.

Factorial Program in Java 2

Factorial Program in Java using Functions

This Java program allows the user to enter any integer value. User entered value will be passed to the Method we created. Within this User defined function, this java factorial program will find Factorial of a given number using the For Loop

// Factorial Program in Java using Functions
package FrequentPrograms;

import java.util.Scanner;

public class FactorialNumberUsingFunctions {
 private static Scanner sc;
 private static long Factorial = 1;
 public static void main(String[] args) {
 int Number; 
 sc = new Scanner(System.in); 

 System.out.println(" Please Enter any number to Find Factorial: ");
 Number = sc.nextInt();
 
 Factorial = FactorialNumber(Number); 
 System.out.format(" Factorial of %d = %d", Number, Factorial);
 }
 
 public static long FactorialNumber (int Number)  {
 int i;
 for (i = 1; i <= Number; i++)  {
 Factorial = Factorial * i;
 }
 return Factorial;
 }
}

OUTPUT

Factorial Program in Java 3

ANALYSIS

In this java factorial program using functions example, We assigned the function return value to a long variable. Because the FactorialNumber(Number); function will return the long value as output.

Factorial = FactorialNumber(Number);

When the compiler reaches to FactorialNumber(Number) line in the main() program, the Jcompiler will immediately jump to below function:

public static long FactorialNumber (int Number)  {

We already explained the LOGIC in the above Java factorial program example.

The last line ends with a return Factorial Statement. It means every time we call the FactorialNumber( ) function it will return factorial value of type long.

Java Factorial Program using Recursion

This Java factorial program using Recursion allows the user to enter any integer value. User entered value will be passed to the Function we created. Within this User defined function, this program will find Factorial of a number Recursively.

In this Java program, we are dividing the code using the Object-Oriented Programming. To do this, first, we will create a class that holds a method to reverse an integer recursively.

package FrequentPrograms;

public class FactorialNumber {
	public long Factorial_Number (int Number)  {
		if (Number == 0 || Number == 1)  {
			return 1;
		}
		else  {
			return Number * Factorial_Number (Number -1);
		}
	}
}

Within the Main Java factorial program, we will create an instance of the above-specified class and call the methods

package FrequentPrograms;

import java.util.Scanner;

public class FactorialNumberUsingRecursion {
 private static Scanner sc;
 public static void main(String[] args) {
 int Number; 
 long Factorial = 1;
 sc = new Scanner(System.in); 

 System.out.println(" Please Enter any number to Find Factorial: ");
 Number = sc.nextInt();
 
 FactorialNumber fn = new FactorialNumber();
 Factorial = fn.Factorial_Number(Number); 
 System.out.format(" Factorial of %d = %d", Number, Factorial);
 }
}

OUTPUT

Factorial Program in Java 4

ANALYSIS

FactorialNumber Class Analysis:

In this java factorial program using Recursion, Within this class, we defined a function. The following function will accept integer values as parameter value and return an integer value

public long Factorial_Number (int Number)  {

Within the user-defined function, We used the If Else Statement to check whether the Given Number is Equal to 0 or Equal to 1.

  • If the condition is TRUE, then the function will return 1.
  • If the condition is False, then the function will return Number * (Number -1) recursively.

User Entered Value = 8

First If statement fails So,

Factorial = Number * Factorial_Number(Number -1);

= 8 * Factorial_Number (8 -1)

= 8 * Factorial_Number (7)

Factorial  = 8 * 7 * Factorial_Number (6)

= 8 * 7 * 6 * Factorial_Number (5)

= 8 * 7 * 6 * 5 * Factorial_Number (4)

Factorial  = 8 * 7 * 6 * 5 * 4 * Factorial_Number (3)

= 8 * 7 * 6 * 5 * 4 * 3 * Factorial_Number (2)

= 8 * 7 * 6 * 5 * 4 * 3 * 2 * Factorial_Number (1)

Factorial  = 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1

= 40320

Placed Under: Java Programs

  • Java Hello World Program
  • Java Add Two Numbers Program
  • Java Compound Interest Program
  • Java Number Divisible by 5 & 11
  • Java Cube of a Number Program
  • Java Print Even Numbers 1 to N
  • Java GCD of Two Numbers
  • Java LCM of Two Numbers
  • Java Largest of Two Numbers
  • Java Largest of Three Numbers
  • Java Print Multiplication Table
  • Java Odd Numbers from 1 to N
  • Java Odd Even Program
  • Java find +Ve or -Ve number
  • Java Power of a Number Program
  • Java Calculate Profit or Loss
  • Java Print 1 to 100 without Loop
  • Java Quadratic Equation roots
  • Java Square of Number Program
  • Java Simple Interest Program
  • Java Sum of Even Numbers
  • Java Sum of Odd numbers
  • Java Sum of Even & Odd Number
  • Java find Total ,Average & Percentage of 5 Subjects
  • Java ASCII Value of a Character
  • Java ASCII Value of all Characters
  • Java String Comparison program
  • Java Area of Circle Program
  • Java Area Of Triangle Program
  • Java Area Of Trapezoid Program
  • Java Area of Equilateral Triangle
  • Java Area of Rectangle Program
  • Java Area of Right angle triangle
  • Java Volume & Surface of Sphere
  • Java Volume & Surface of Cone
  • Java Volume & Surface of Cuboid
  • Java Volume & Surface of Cube
  • Java Cylinder Volume & Surface
  • Java Math Library
  • Java Armstrong Number Program
  • Java Perfect Number Program
  • Java Palindrome Program
  • Java Count Digits in a Number
  • Java Calculate Electricity Bill
  • Java Find Factors of a Number
  • Java Factorial Program
  • Java Fibonacci Series program
  • Java find First Digit of a Number
  • Java find Last Digit of a Number
  • Java First & Last Digit of Number
  • Java Generic Root of Number
  • Java Natural Numbers in Reverse
  • Java Natural Numbers from 1 to N
  • Java Find Sum of Prime Numbers
  • Java Print Prime Numbers 1 to N
  • Java Prime Number Program
  • Java Reverse a Number Program
  • Java Strong Number Program
  • Java Sum of N Natural Numbers
  • Java Sum of Digits Program
  • Java Swap Two Numbers
  • Java Leap Year Program
  • Java Number of Days in a Month
  • Java Array
  • Java Array Arithmetic Operations
  • Java Program to Copy an Array
  • Java Count Array Duplicates
  • Java count even number in array
  • Java count odd numbers in Array
  • Java Count Even & Odds in Array
  • Java Count Negative Array Items
  • Java Count Positive Array Items
  • Java Count Array +Ve & -Ve num
  • Java Delete Array Duplicates
  • Java Large & Small Array Item
  • Java Largest Array Number
  • Java Print Array Elements
  • Java Print Positive Array Items
  • Java Print Negative Array Items
  • Java Smallest Array Number
  • Java Second Largest Array Item
  • Java Print Unique Array Items
  • Java +Ve & -Ve in separate array
  • Java Sort Array in Descending
  • Java Sort Array in Ascending
  • Java Sum of Array Elements
  • Java Sum of Array Even Numbers
  • Java Sum of Array Odd Numbers
  • Java Sum of Array Even and Odd
  • Java Swap Arrays without temp
  • Java Matrix Introduction
  • Java Print Matrix items
  • Java Check 2 Matrices are Equal
  • Java Matrix Arithmetic operation
  • Java Matrix Addition
  • Java Matrix Multiplication
  • Java Find Matrix Determinant
  • Java Identity Matrix
  • Java Interchange Matrix diagonal
  • Java Matrix Lower Triangle
  • Java Matrix Lower Triangle Sum
  • Java Matrix Upper Triangle
  • Java Matrix Upper Triangle Sum
  • Java Scalar Matrix Multiplication
  • Java Sparse Matrix
  • Java Sum of Matrix Diagonal
  • Java Sum of Matrix Opp Diagonal
  • Java Sum of each Matrix Row
  • Java Sum of each Matrix Column
  • Java Sum of Matrix row & column
  • Java Symmetric Matrix
  • Java Transpose Matrix
  • Java Rectangle Star Pattern
  • Java Square Star Pattern
  • Java Hollow Box Number Pattern
  • Java Box Number Pattern of 1, 0
  • Java Square Number Pattern
  • Java Print Floyd’s Triangle
  • Java Print String Characters
  • Java String replace 1st Char Occ
  • Java String replace last Char occ
  • Java String remove 1st Char Occ
  • Java string remove last Char Occ
  • Java String remove 1st, last char
  • Java String remove all char occur
  • Java String Find 1st Char Occur
  • Java String find all char occur
  • Java String Find Last Char Occur
  • Java String Print 1st & last Char
  • Java String Chars ASCII values
  • Java Program to Concat Strings
  • Java String Characters count
  • Java Count Total Char Occur
  • Java Max Occur String Character
  • Java Toggle String Characters
  • Java Frequency of each Char
  • Java Count Vowels & Consonants
  • Java Count alph digits, special
  • Java Palindrome String
  • Java Program to Reverse a String
  • Java Min Occur String character
  • Java Convert Lower to Upper
  • Java Convert Upper to Lower
  • Java Count total String words
  • C Tutorial
  • C# Tutorial
  • Java Tutorial
  • JavaScript Tutorial
  • Python Tutorial
  • MySQL Tutorial
  • SQL Server Tutorial
  • R Tutorial
  • Power BI Tutorial
  • Tableau Tutorial
  • SSIS Tutorial
  • SSRS Tutorial
  • Informatica Tutorial
  • Talend Tutorial
  • C Programs
  • C++ Programs
  • Java Programs
  • Python Programs
  • MDX Tutorial
  • SSAS Tutorial
  • QlikView Tutorial

Copyright © 2021 | Tutorial Gateway· All Rights Reserved by Suresh

Home | About Us | Contact Us | Privacy Policy