Calculating factorial using recursion in Java

In this tutorial, we will see how to calculate the factorial of a number using recursion in Java programming language.

The factorial of any given number is the product of all the numbers starting from the given number till we reach 1.

We can calculate factorial of any given number using recursion or iteration in java. In iteration, we can directly take a for loop initialize the loop variable with the given number and decrease it till we reach 1. We must keep on storing the value in a variable, taking the product for each iteration.

However, recursion can be a bit tricky. Recursion is a method of solving a particular problem in which we calculate the solution only by using a smaller instance of the same problem. In programming, recursion using a function that calls itself directly or indirectly and that corresponding function is called as recursive function.

Java Program to calculate factorial

Now see the program below:

import java.util.*;
public class Main{
static int calc_factorial(int num)
{
int result;
if(num==1){
return 1;
}
result= calc_factorial(n-1)* n;
return result;
}
public static void main(String args[])
{
Scanner scanner = new Scanner(System.in);
System.out.println("Enter number:");
int number = scanner.nextInt();
int factorial = calc_factorial(number);
System.out.println("Factorial is: "+factorial);
}

}

In this program, we will first take the input for the number from the user using Scanner class. We use nextInt() function is to take input in the form of an integer. We will then pass it as the parameter to our function calc_factorial() which is a recursive function to calculate the factorial of the number.

There are two parts in a recursive function:

  1. base condition
  2. recursive condition

Base condition for this function is that it will terminate and return 1 when the value of number is 1. Since, we know that factorial of 1 is: 1.

While the recursive condition, we call the function itself, but each time the value of the parameter is decremented by 1 and multiply it with the current value of the parameter. Hence, after each method call is executed we will get the product of all the numbers till 1 stored in our variable result. Finally, we will return this value to the main method where we will print the value of factorial.

 

Output:

Enter number: 4

Factorial is: 24

Also read,

Leave a Reply

Your email address will not be published. Required fields are marked *