Understanding Java Recursion...Factorial Example

In one line if someone wanted to explain,
"Recursion is, the method that call itself". Easy enough ehy...

If the input number is 0 or 1, we are returning 1 else we are going to compute the result as
n! = n * (n-1)!
A simple mathematics formula.

Here I am going to create the static method so, I don't have to create an instance of the method and can call just with the method name.

Note:
Here the datatype that I'm using is int so, ofcourse it may have some limitations and hence you can't go beyond certain limit however you guys may go ahead and have it double, long etc.

Let's have a look at the way we can code for any factorials using Java Recursion concept.

public class RecursionExample {

 private static int factorial(int input) {
  int fact = 0;
  if (input <= 1)
   fact = 1;
  else
   fact = input * factorial(input - 1);

  return fact;
 }

 public static void main(String[] args) {
  System.out.println(factorial(5));
 }
}
The above example will print out 120 as an output.

No comments:

Post a Comment