In this section you will learn how to find the factorial of a number.
Java Factorial Program Using Recursion
In this section you will learn how to find the factorial of a number.
Here I am giving a simple example which is concern for finding the factorial of a number. In mathematics factorial is defined as n! = n*(n-1)...2*1. where, n is a natural number and n ≥ 1. Value of 0! is 1. for example 5! = 5*4*3*2*1.
Factorial.java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
class Factorial
{
long fact(long a)
{
if(a <= 1)
return 1;
else
{
a= a*fact(a-1);
return a;
}
}
public static void main (String arr[]) throws IOException
{
System.out.println("Enter a number to find factorial");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int num = Integer.parseInt( br.readLine());
Factorial f = new Factorial();
System.out.println(f.fact(num));
}
}
Output :
When you will execute the above example you will get the output as :


[ 0 ] Comments