Write a recursive function to find factorial of a number.
According to definition,
n! = n*(n-1)!
Yes, the definition is recursive. Which makes our coding easier.
Recursive function
A function which invokes or calls itself is called a recursive function. Just like the definition given above, you write factorial(n-1) within factorial(int n) function.Now you may wonder, won't this type of function cause an infinite loop? It does, unless you create a base condition in which there is no recursive call.
In this example, n = 0 is the base condition. So 0! is 1 and if n is 0 we just return 1.
Here is how we have to write our recursive function for factorial.
- if n >0 return n* factorial(n-1)
- if n =0 return 1
Here is our complete function in Java
int factorial(int n){ if(n==0) return 1; return n*factorial(n-1); }
Comments
Post a Comment