Source of Factorial.java


  2: /**
  3:  * A program that uses recursion to calculate factorials.
  4:  *
  5:  * @author Mark Young (A00000000)
  6:  */
  7: public class Factorial {

  9:     public static void main(String[] args) {
 10:         System.out.println("\n"
 11:                 + "The factorials from 1 to 10\n"
 12:                 + "---------------------------\n");
 13:         for (int i = 1; i <= 10; ++i) {
 14:             System.out.println(i + "! == " + factorial(i));
 15:         }
 16:         System.out.println("\n\n");
 17:     }

 19:     /**
 20:      * Calculate the factorial of n.
 21:      * (Uses recursion.)
 22:      *
 23:      * @pre  num >= 0 and num! <= Integer.MAX_VALUE
 24:      * @post return value is num!
 25:      *
 26:      * @param num the number to calculate the factorial of.
 27:      * @reurn the factorial of num (num!)
 28:      */
 29:     public static int factorial(int num) {
 30:         if (num <= 1) {
 31:             return 1;
 32:         } else {
 33:             return num * factorial(num - 1);
 34:         }
 35:     }

 37: }