Factorial of a number in Java using recursion
In this post, you will learn how to find the factorial of a number using the Java programming language.
The factorial is normally used in different areas of mathematics, including algebra, mathematical analysis, and Combinations and Permutations. The factorial of a number n is denoted by n!. This is the product of all positive numbers less than or equal to n. It is calculated as-
n! = n X (n-1) X (n-3) X ……… X 3 X 2 X 1
Example of factorial
Suppose we want to get a factorial of 7, then the factorial will be-
7! = 7 X 6 X 5 X 4 X 3 X 2 X 1
5040
Program1: Find factorial of a number using recursion in Java
Here is the Java program to find the factorial of a number using the recursion function. A recursion function is a function that is called by itself. If the number is equal to 0, it returns 1. The factorial of a number less than equal to 0 does not exist. If the number is greater than 1, the function calls recursively and finds the factorial of the number.
public class FindFactorial{
static int factorial(int num){
if(num == 0)
return 1;
else
return(num * factorial(num-1));
}
public static void main(String args[]){
int i,fact=1;
int number=4;
fact = factorial(number);
System.out.println("Factorial of "+number+" is: "+fact);
}
}
Output of the above code:
Factorial of 6 = 720
Program2: Find the factorial of a number using user input in Java
In the given Java program, we ask the user to provide the number and then calculate the factorial of the given number using recursion.
import java.util.Scanner;
public class FindFactorial{
static int factorial(int num){
if(num == 0)
return 1;
else
return(num * factorial(num-1));
}
public static void main(String args[]){
int i,fact=1;
int num;
// Getting value from user
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number: ");
num = sc.nextInt();
fact = factorial(num);
System.out.println("Factorial of "+num+": "+fact);
}
}
Output of the above code:
Enter the number: 8
Factorial of 8: 40320
Related Articles
Sort array in ascending order JavaAutomorphic number in Java
Pascal triangle program in Java
Factorial using recursion in java
Java random number between 1 and 10
Palindrome program in Java
Floyd triangle in Java
Pyramid pattern programs in Java
Star pattern programs in Java
Number pattern programs in Java
Java program to find area of rectangle
Matrix multiplication in Java
Electricity bill program in Java
Java program to find area of triangle
Area of circle program in Java
Remove duplicate elements from array in Java
Capitalize first letter of each word Java
Convert binary to decimal in Java
Convert decimal to binary in Java
Convert decimal to octal in Java
Convert decimal to hexadecimal in Java
Simple interest program in Java