Factorial
factorial of any number is calculated in the following way.
n! = 1*2*3*4*5*……….*n
but there is some rule or important point related to factorial
factorial of 0 is 1, so we can use this as a termination for recursion
Recursive Function/Method to Calculate Factorial
int factorial (n)
{
if(n==0)
return 1;
else return n* factorial(n-1);
}
Java Code to Calculate Factorial Using Recursion
import java.util.Scanner;
public class FactorialUsingRecursion{
// recursive method to calculate factorial
static int factorial(int n)
{
if(n==0)
return 1;
else return n*factorial(n-1);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter any non negative integer to calculate factorial");
int n = sc.nextInt();
System.out.println("factorial of "+n+" is "+factorial(n));
}
}
Output –
Factorial of 12 is calculated by multiplying 12*11*10*9*8*7*6*5*4*3*2*1*1
we can use this same logic in all other programming languages like C, C++,Python etc to calculate factorial using recursion.
Similar Java Tutorials
- Odd Even in Java
- Method to print exception information in Java
- Exception Handling by Using try-catch in Java
- Checked Exception vs Unchecked Exception
- Exception Hierarchy in Java
- Java Exception Handling Interview Questions
- final finally finalize in java
- User Defined Exception in Java
- Exception Handling Keyword in Java
- throw throws in Java
- try with multiple catch block in Java
- Threads in Java
- Thread priority in Java