Calculate a Factorial of a number – Java

Write a Java program to calculate a Factorial of a number.

- Advertisement -

The factorial of a number is the product of all the positive numbers less than or equal to the number. The factorial of a number n is denoted by n!

Now, let’s write a program and find a factorial of a number using recursion.

- Advertisement -

package Rootuser;
import java.util.Scanner;
public class Factorial {
public static void main(String args[]){
//Scanner object for capturing the user input
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number:");
//Stored the entered value in variable
int num = scanner.nextInt();
//Called the user defined function fact
int factorial = fact(num);
System.out.println("The factorial of the entered number is: "+factorial);
}
static int fact(int n)
{
int output;
if(n==1){
return 1;
}
//Recursion: Function calling itself!!
output = fact(n-1)* n;
return output;
}
}

On executing the above program, you will get factorial of a number as shown below:

Enter the number:
5
The factorial of the entered number is: 120

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. AcceptRead More