/**Demonstration of three types of recursion
 *
 * @author TK Rogers
 * @version 10-16-08
 */
public class RecursiveMultiplication {
    public static void main ( ) {
        System.out.println ( "Note that \"a\" remains constant while \"b\"
                                       decreases by 1 in each iteration." ) ;
        System.out.println ( "4 x 2 = " + multiply ( 4, 2 ) + "\n" ) ;
                                                                                   // ^ creates a new line.
        System.out.println ( "Note that \"name\" remains constant while \"n\"
                                        decreases by 1 in each iteration." ) ;
        hi ( "Bob" , 3 ) ;
        System.out.println ( "\nNote that \"x\" decreases by 1 in each iteration." ) ;
        System.out.println ( "       Total = " + addFractions ( 3 ) ) ;
    }
 
    /** Purpose: Method returns a * b
     *  Preconditions: two integers
     *  Postconditions: returns a * b.
        */
    public static int multiply ( int a , int b ) {
        System.out.println ( "a = " + a + ", b = " + b ) ;
        if (b <= 1) { //stops the recursion
            return a ;
        }
        return a + multiply ( a, b - 1 ) ;
    }
     /**Purpose: Method causes "hello " + name to be output on n lines
     *  Preconditions: a string representing a name to output, an integer
     *                           representing the number of times the sting is output.
     *  Postconditions: none.*/
    static int hi ( String name, int n ) {
        if ( n == 0 ) { //stops the recursion
            System.out.println ( "saying hello to " + name + " has stopped, n = " + n ) ;
            return 0;
        }
        System.out.println ( "hello " + name + ", n = " + n ) ;
        return hi ( name, n - 1 ) ;               
    }
 
    /**Purpose: Method returns the series 1/1 + 1/2 + 1/3 + ... + 1/x
     * Preconditions: an integer x for the above series
     * Postconditions: returns the value for the above series. */
    static double addFractions ( int x ) {
        System.out.println ( "x = " + x + ", 1.0 / x = " + 1.0 / x) ;
        if ( x <= 1 ) return 1.0 ; //stops the recursion
        else return 1.0 / x + addFractions ( x - 1 ) ;
 
          // If x = 3, the recursion runs as follows:
      // return  1.0 / 3 + addFractions ( x-1 ) ;
                                    // return  1.0 / 2 + addFractions ( x-1 ) ;
                                                       // return  1.0 / 1;
                                                             // At this point, the computer adds 
                                                             //  the 3 bold print values from
                                                             // bottom to top.
    }
}