Write a Java program to calculate factorial of a number using recursion
- Import the java.util.* package which includes the Scanner class that is used to get user input.
- Define a class called Factorial.
- In the main method, create an instance of the Scanner class to read user input, and then prompt the user to enter a number.
- Read the integer input from the user and assign it to the variable n.
- Call the factorial method and pass the value of n as an argument, and assign the returned value to the variable fact.
- Print the calculated factorial using the System.out.printf method.
- Define a method called factorial that takes an integer argument n and returns an integer value.
- Inside the factorial method, check if the value of n is equal to 1. If it is, then return 1.
- If n is not equal to 1, then calculate the factorial by recursively calling the factorial method with the argument n-1, and multiply the result with n.
- Return the calculated factorial value.
Source Code
import java.util.*;
public class Factorial
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int n,fact = 0;
System.out.print("Enter the Number: ");
n = input.nextInt();
fact = factorial(n);
System.out.printf("Factorial is : " + fact);
}
public static int factorial(int n)
{
if(n == 1)
{
return 1;
}
else
{
return n * factorial(n - 1);
}
}
}
Output
Enter the Number: 6
Factorial is : 720