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.

2 comments:

  1. Thanks for the post, I am techno savvy. I believe you hit the nail right on the head. I am highly impressed with your blog. It is very nicely explained. Your article adds best knowledge to our Java Online Training from India. or learn thru Java Online Training from India Students.

    or learn thru JavaScript Online Training from India. Appreciating the persistence you put into your blog and detailed information you provide. Kindly keep blogging.

    ReplyDelete
  2. Thanks for the post, I am techno savvy. I believe you hit the nail right on the head. I am highly impressed with your blog. It is very nicely explained. Your article adds best knowledge to our Java Online Training from India. or learn thru Java Online Training from India Students.

    or learn thru JavaScript Online Training from India. Appreciating the persistence you put into your blog and detailed information you provide. Kindly keep blogging.

    ReplyDelete