Factorial using recursion program

Simple java program for factorial using recursion with explanation. Easy logic, can be used in C#(sharp), python, php, perl... etc.

int fact(int n)
{
int result;
if(n==1)
{
return 1;
}
result=fact(n-1)*n;
return result;
}

Understand the logic behind recursion, so you don’t feel factorial using recursion as difficult.

Input -5, Output – 120.

Explanation:

How to find factorial of number 5 using recursion.

Recursion – Function call itself.

Example 1:

Take n=5, we gonna find factorial for number 5.

line 8: fact(5-1)*5 => fact(4)*5

Now four is passed as an argument to the method fact i.e fact(4).

( fact(4-1)*4)*5 => fact(3)*4*5

Now three is passed as an argument to method fact.

fact(2)*3*4*5

Now two.

fact(1)*2*3*4*5

when 1 is passed as an argument the line6, will be executed. so the

result become 1*2*3*4*5 => 120

 

Therefore factorial of 5 is 120.

 

Simple java program to find factorial of first 10 numbers