16 lines
366 B
Markdown
16 lines
366 B
Markdown
Recursion via factorial function
|
|
```java
|
|
int fact(int n)
|
|
{
|
|
int result;
|
|
if(n==0 || n==1)
|
|
return 1;
|
|
|
|
result = fact(n-1) * n;
|
|
return result;
|
|
}
|
|
```
|
|
Since factorial(0) or factorial(1) is just 1, we return 1 in these scenarios
|
|
If we have factorial(2), we would do factorial(1)\*2 = 2
|
|
fact(5) = factorial(4) \* 5 = 5\*4\*3\*2\*1 = 120
|