×

Factorial Program in Java using Recursion

Factorial Program in Java

Factorials are used in mathematics to calculate permutations and combinations. It is denoted by the exclamatory symbol (!). Suppose, p is a number whose factorial is to be calculated is represented by p!.It is pronounced as p factorial. In this section, we will create a Java program to calculate the factorial of a number using iterative and recursive approach.   

Factorial of any number is the multiplication of numbers from that particular number to 1 either in increasing or in decreasing order. In general terms, we can represent the factorial of a number as follows:

p! = p × (p-1) × (p-2) × … × 1 or 1 × … × (p-2) × (p-1) × p

For example:

3! = 3 × 2 × 1 or 1 × 2 × 3 = 6

4! = 4 × 3 × 2 × 1 or 1 × 2 × 3 × 4 = 24

Note: As per standard mathematical definition, the factorial of any negative number cannot be found. Also, 0! is always 1.

Let’s write a Java program that calculates the factorial of a number using Java for loop.

Iterative Approach

Filename: FactorialProgramExample.java

public class FactorialProgramExample
{
public static void main(String[] args)
{
int j, factorial = 1; 
int no = 6; //we are calculating factorial of the number assigned to the variable   
for(j=1; j <= no; j++)
{   
factorial = factorial * j;   
}   
System.out.println("Factorial of the number "+ no +" is: " + factorial);
}
}

Output:

Factorial of the number 6 is: 720

In the above example, the variable factorial initialized to 1. We have used the Java for loop to find the factorial of a number. The loop executes until the condition j <= no becomes false. After each iteration, the variable j increments by 1. The for loop executes in the following order:

First iteration: The variables factorial = 1, and j = 1.

factorial = factorial * j => factorial = 1×1 = 1

Second iteration: After the first iteration, the value of factorial become 1 and the value of j incremented by 1 i.e. 2.  Hence, factorial = 1, and j = 2.

factorial = factorial * j => factorial = 1×2 = 2

Third iteration: After the second iteration, the value of factorial become 2 and the value of j incremented by 1 i.e. 3. Hence, factorial = 2, and j = 3.

factorial = factorial * j => factorial = 2×3 = 6

Fourth iteration: After the third iteration, the value of factorial become 6 and the value of j incremented by 1 i.e. 4. Hence, factorial = 6, and j = 4.

factorial = factorial * j => factorial = 6×4 = 24

Fifth iteration: After the fourth iteration, the value of factorial become 24 and the value of j incremented by 1 i.e. 5. Hence, factorial = 24, and j = 5.

factorial = factorial * j => factorial = 24×5 = 120

Sixth iteration: After the fifth iteration, the value of factorial become 120 and the value of j incremented by 1 i.e. 6. Hence, factorial = 120, and j = 6.

factorial = factorial * j => factorial = 120×6 = 720

After the sixth iteration, the value of factorial become 720 and the value of j incremented by 1 i.e. 7. Now the condition j <= no becomes false. The loop will terminate and thus, we get 6! = 720.

Recursive Approach

We can also use the recursive approach to find the factorial. The demonstration is given below.

Filename: FactorialProgramExample1.java

public class FactorialProgramExample1
{
static int findFactorial(int n)
{
if (n == 0 || n == 1)
return 1;
if(n < 0)
return -1;
return n * findFactorial(n-1);  //recursively called function
}
public static void main(String[] args)
{
int j, factorial = 1; 
int num = 6; //a number whose factorial is to be calculated   
factorial = findFactorial(num);  
if(num >= 0)
System.out.println("Factorial of the number "+ num +" is: " + factorial);
else
System.out.println("The given number is negative. Hence, the factorial cannot be found.");
}
}

Output:

Factorial of the number 6 is: 720

Explanation: Here, the recursive approach worked because we can also write 6! as 6 × 5! and 5! as 5 × 4! and so on. The findFactorial() method finds the factorial of the number passed to its argument. So, if we pass 6 in the method argument, then the method will find the factorial of 6, and if 5 is passed, the method will find the factorial of 5. Therefore, we can say

findFactorial(6) = 6 × findFactorial(5)

findFactorial(5) = 5 × findFactorial(4)

findFactorial(4) = 4 × findFactorial(3)

findFactorial(3) = 3 × findFactorial(2)

findFactorial(2) = 2 × findFactorial(1)

findFactorial(1) = 1

Combining all the above, we get:

findFactorial(6) = 6 × 5 × 4 × 3 × 2 × 1 = 720.


Related Topics

Java ResultSetMetaData

The data about another data is called Metadata. The ResultSetMetaData is used to store the data about ResultSet. The ResultSet Contains the columns, rows, names of table, datatypes etc. these...

2 minutes read.

Object Definition in Java

In this article, you will be acknowledged about object in Java, its definition and how is this useful in writing the programs in Java. The comprehension of object-oriented technology depends on...

4 minutes read.

Java Boyer Moore

A string searching or matching technique called the Boyer-Moore algorithm was created in 1977 by Robert S. Boyer and J. Strother Moore. It is the most popular and effective string-matching...

9 minutes read.

Fibodiv Number in Java

Before understanding the concept of the fibodiv number, one should realize what the Fibonacci number is. What are Fibonacci Numbers? The Fibonacci sequence of whole numbers is composed of the numbers 0,...

5 minutes read.

Java Queue Interface

Queue interface is a subtype of Collection interface. All methods in the Collection interface are also available in the Queue interface. It provides operations of Collection and also some additional...

2 minutes read.

Java ArrayList

Java ArrayList Class A Java ArrayList class is a dynamic array which is used to store the elements. It is a part of collection framework. It implements the List Interface and inherits the...

12 minutes read.

How to compare characters in Java

In this tutorial, we will learn about how to compare characters in Java. To compare characters in Java, we will learn about what is a character in Java Char The character is...

4 minutes read.

Sublime Number in Java

In this tutorial, we will understand what is meant by sublime number in java. From the point of the coding interview, it is one of the important topics. We will we will...

4 minutes read.

Thread States in Java

An Item's Life Cycle (Thread States) A thread can be in any of the states mentioned above at any given time in Java. They are as follows: New Active I'm blocked or waiting Temporary...

3 minutes read.

Java throw

Java throw Sometimes it is required in the code to throw an exception deliberately. In order to achieve the same, the Java throw keyword should be used. One can throw either...

3 minutes read.

Convert Integer to Roman Numerals in Java

The main objective of this article is to convert the integers that are decimal values to the roman numbers. Problem statement: Write a software/program/code to convert any integer to a roman number. You...

10 minutes read.

The Maximum Rectangular Area in a Histogram in Java

Continuous bars should be used to form the largest possible rectangle. We'll assume in the interest of convenience that each bar's width is 1. Naive Approach In this method, each bar will be...

6 minutes read.

Converting Long to Date in Java

What Long and Date are in Java and how are they implemented in the Java programming language are the topics of this article. Additionally, we'll go into great detail on...

4 minutes read.

Upcasting and Downcasting in Java

Type casting in Java is an important and very interesting topic to deal with. But here upcasting and downcasting is somewhat related to typecasting. In normal typecasting, we convert from...

6 minutes read.

Java program to find frequency of characters in a string

In this article, you will understand the how to find the frequency of characters in strings by using Java programming language. Along with this, you will understand the hashing concept...

3 minutes read.

How to download Eclipse for Java

Introduction: We write a java program, and when we want to run it, we need software to run it. Eclipse is a kind of software used to execute a JavaFX...

3 minutes read.

Tilt operator in Java | Tilde operator in Java Example

The symbol designates it as a unary operator (pronounced as the tilde). It gives back the bit's complement or inverse. Every 0 turns into a 1, and every 1 back...

3 minutes read.

How to Split String by Comma in Java

strsplit() technique permits you to break a string given the explicit Java string delimiter. The Java string split property is frequently a space or a comma(,) that you want to...

7 minutes read.

How to convert String to String array in Java

A String in Java is a thing that indicates a collection of letters. We must include the String class from java.lang package if we want to be using strings. An...

5 minutes read.

Diamond problem in Java

The Diamond Problem in Java is connected to multiple inheritances. It is also referred to as the "deadly diamond dilemma" or even the "deadly diamond of death”. The solution for...

5 minutes read.