Thursday, June 20, 2013

Recursion

Recursion simply provides a method  with the ability to reference itself.  In the factorial example (5 *4 *3 *2 *1) the factorial method will reference itself as long as i != 1.  Thus, the following will return 120.

Class Recursion{

int factorial(int i){
  if(i==1){
  return 1;
  }
  else {
  return i * factorial(i-1);
  }
}

}


int imaInt;

Recursion curseLikeAPirate = new Recursion();

imaInt = curseLikeAPirate.factorial(5);

No comments: