Print Page Print Page

CH6 – More Recursion

  1. Create a new class named Factorial.
  2. Add the method factorial.
public class Factorial{
  public static int factorial(int n){
    if(n==0){
      return 1;
    }
    int recurse = factorial(n-1);
    int result = n * recurse;
    return result;
  }
}
  1. Add a main method and have it call the factorial method.
public static void main(String[] args){
  int value = Integer.parseInt(args[0]);
  int factValue = Factorial.factorial(value);
  System.out.println("factorial of " + value + " is " + factValue);
}
  1. Compile and run the program.
$ javac Factorial.java 
$ java Factorial 12
factorial of 12 is 479001600

The complete class should appear as follows.

public class Factorial{
  public static int factorial(int n){
    if(n==0){
      return 1;
    }
    int recurse = factorial(n-1);
    int result = n * recurse;
    return result;
  }
  public static void main(String[] args){
    int value = Integer.parseInt(args[0]);
    int factValue = Factorial.factorial(value);
    System.out.println("factorial of " + value + " is " + factValue);
  }
}