Recursive factorial method

Started by magesh.p, Aug 14, 2008, 07:20 PM

Previous topic - Next topic

magesh.p

Recursive factorial method

public class MainClass {
  public static void main(String args[]) {
    for (int counter = 0; counter <= 10; counter++)
      System.out.printf("%d! = %d\n", counter, factorial(counter));

  }

  // recursive declaration of method factorial
  public static long factorial(long number) {
    if (number <= 1) // test for base case
      return 1; // base cases: 0! = 1 and 1! = 1
    else
      // recursion step
      return number * factorial(number - 1);
  }
}

Result :

0! = 1
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
8! = 40320
9! = 362880
10! = 3628800
- An Proud Acumen -