//=======================================================================================
// Loops vs. Recursion - Computing the future value of an amount (compounded monthly)
// Example:  The future value of $1000 for 60 months (5 years) at 3% is $1162  
//=======================================================================================
public class recursion
{
    public static void main(String[] args)
    {
        int amount      = 10000;                                    //loan amount
        int months      = 120;                                      //duration in months (10 years)
        double interest = .05;                                      //interest rate
        double result;
        long start, end;
                
        start  = System.nanoTime();
        result = computeLoop(amount, months, interest);             //using loops
        end    = System.nanoTime();

        System.out.printf ("Loop  duration: %6.3f microseconds \n" , (end-start)/1000.0);
        System.out.println(result + "\n");

        start  = System.nanoTime();
        result = computeRecursive(amount, months, interest);        //using recursion   
        end    = System.nanoTime();

        System.out.printf ("recur duration: %6.3f microseconds \n" , (end-start)/1000.0);
        System.out.println(result + "\n");
    }
    
//=== Using loops =======================================================================

    public static double computeLoop(double amount, int months, double interest)
    {        
        for (int i=1; i<=months; i++)
            amount = amount * (1 + interest/12);

        return(amount);
    }
          
//=== Using Recursion ===================================================================

    public static double computeRecursive(double amount, int months, double interest)
    {        
        if (months == 0)
            return(amount);                                         //end of recursion                              
        
        amount = amount * (1 + interest/12);
        amount = computeRecursive(amount, months-1, interest);      //recursive call 

        return(amount);         
    }
}