/*
payment.c

A program to demonstrate a function which accepts multiple
parameters of different types, and which returns a non-int
type.

This program calculates payments for a loan.

Ray Ontko, 1999/10/10
*/

#include <stdio.h>

float payment( float , float , int ) ;

main()
{
printf( "payment = %.2f\n" , payment( 6000.00 , 8.0 , 60 ) ) ;
}

float payment( float principal , float rate , int months ) 
{
/*
Calculates the payments for a loan, given a principal balance,
a percentage interest rate, and a number of months. 
*/
float mrate ;
float low ;
float high ;
float balance ;
float pmt ;
int m ;

/* calculate a monthly rate */
mrate = 1.0 + ( rate / 100.0 ) / 12.0 ;

/* establish a lower and upper bound for the payments */
low = principal / (float)months ;
high = low + principal * ( ( rate / 100.0 ) / 12.0 ) ;

/* pick an initial payment amount as the midpoint between
   the upper bound and the lower bound */
pmt = ( high + low ) / 2.0 ;

/* while the difference between our upper bound and lower
bound is greater than half-a-penny... */
while ( ( high - low ) > 0.005 )
  {
  /* "simulate" interest and payments on the loan */
  balance = principal ;
  for ( m = 0 ; m < months ; m ++ )
    {
    balance *= mrate ;
    balance -= pmt ;
    }
  /* if the balance is negative, we overpaid and should reduce our
     upper bound to the payments we just tried.  Otherwise, set the
     lower bound to the payments we just tried. */
  if ( balance < 0 )
    high = pmt ;
  else
    low = pmt ;
  /* calculate a new payment amount and repeat the process.
  pmt = ( high + low ) / 2.0 ;
  }

/* return the last payment amount (which should be within .25 cents
of the exact solution) */
return pmt ;
}
