Recursion in Java

Recursion is used when a problem can be reduced into one or several problems of the same nature, but a smaller size. This process is usually repeated until a boundary situation is reached, where the problem can be directly solved. Java supports recursive methods, i.e. even if you're already inside methodA() you can call methodA(). 

Example (A Recursive Counterpart of the previous Factorial Method)
n! is defined as n times n-1 times n-2 times n-3 ... times 2 times 1 where n is a positive integer. 0! is defined as 1. As you see n! = n time (n-1)!. This lends itself to recursive calculation, as in the following method:

public static long factorial (int n) {
  if (n < 0) {
    return -1;
  } 
  else if (n == 0) {
    return 1;
  }
  else {
    return n*factorial(n-1);
  }
}

0 comments:

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More