;

Java Program to Find the Factorial of a Number Using Recursion


Tutorialsrack 06/11/2021 Java

In this Java program, you’ll learn how to find the factorial of a number using a recursion function. In this program, we used the following Java basics such as if...else conditions, and java recursion methods.

What is a Factorial Number?

In mathematics, the factorial of a positive integer n, denoted by n!, is the product of all positive integers less than or equal to n:

n!=(n-1)x(n-2)x(n-3)x…3x2x1

The factorial, symbolized by an exclamation mark (!), is a quantity defined for all integers greater than or equal to 0.

For example,

5!=5x4x3x2x1=120

6!=6x5x4x3x2x1=720

The value of 0! is 1.

Here is the code of the program to print factorial of a number using Recursion:

Example - Java Program to Find the Factorial of a Number Using Recursion
//Java Program to Find Factorial of a Number Using Recursion

import java.util.Scanner;

public class JavaPrograms {

	public static void main(String[] args) {
		int number;

		// create an object of Scanner class
		Scanner sc = new Scanner(System.in);

		// ask users to enter numbers
		System.out.println("Enter a number: ");
		number = sc.nextInt();
		long factorial = factorial(number);
		System.out.println("Factorial of " + number + " = " + factorial);
		sc.close();
	}

	public static long factorial(int num) {
		if (num >= 1)
			return num * factorial(num - 1);
		else
			return 1;
	}

}
Output

Enter a number: 

5

Factorial of 5 = 120

Working of Program

  • First, we take the input from the user and the number whose sum is to be found is stored in a variable number.
  • Initially, the factorial() is a recursive function that is called from the main() function and we take 5 as input and pass it as an argument.
  • Since 6 is greater than or equal to 1, 5 is multiplied to the result of factorial() where 4 (num -1) is passed. Since it is called from the same function, it is known as a recursive call.
  • In each recursive call, the value of the argument num is decreased by 1 until num reaches less than 1.
  • When the value of num is less than 1, there is no recursive call.
  • And each recursive calls returns giving us:
  • 5 * 4 * 3 * 2 * 1 * 1 (for 0) = 120


Related Posts



Comments

Recent Posts
Tags