home Sandy, UT
Wednesday, 2017.11.22
04:20 MDT [GMT-7]
Brionews - Company Logo Condition: Partly Cloudy
Temperature: 4°C (39.2°F)
Barometer: 1029 mb and rising
IT
MIX
News
Low Cost Affordable C C++ PHP mySQL Perl Programs Development
July 31st, 2004

A Loan Interest Calculator

In a Unix class we were assigned this program.
The original code calculates the interest and the number of fixed amount monthly payments on a loan.
Assignment was to transform the monthly payment in an array with different possible monthly amounts.
Usage: loan -r -a -p

-a amount borrowed
-r rate of interest
-p amount of the monthly payment (also with different amounts)

Ex. 1: perl loan -r 10 -a 600 -p 90
Ex. 2: perl loan -p 100 -r 4.75 -p 95 -a 955 -p 90 -p 100 -p 85 -p 80 -p 75 -p 70 -p 60
Ex. 3: perl loan -p 111 -r 5.52 -p 99 -a 1153 -p 95 -p 105 -p 90 -p 80 -p 80 -p 75 -p 75 -p 70 -p 60

# show loan interest
# version 2: multiple payments
#

$i = 0;
$payIndex = 0;
# @PAYMENT[0] = 0; 	# ? is it really necessary??

while ( $i < $#ARGV )
{
	if ( @ARGV[$i] eq "-r" )
	{
		$RATE=@ARGV[++$i];
	}
	else
	{
		if ( @ARGV[$i] eq "-a" )
		{
			$AMOUNT=@ARGV[++$i];
		}
		else
		{
			if ( @ARGV[$i] eq "-p" )
			{
				@PAYMENT[$payIndex++]=@ARGV[++$i];
			}
			else
			{
				print "Unknown argument (@ARGV[$i])\n";
			}
		}
	}
	$i++;
}

if ( $AMOUNT == 0 || $RATE == 0 || @PAYMENT[0] == 0 )
{
	print "Specify -r rate -a amount -p payment\n";
	exit;
}

# echo clear;
print "Original Balance: \$$AMOUNT\n";
print "Interest Rate   : ${RATE}%\n";
print "Monthly Payment : \$@PAYMENT\n";
print "\n";
print "Month\tPayment\tInterest\tPrincipal\tBalance\n\n";

$month=1;
$rate=$RATE/12/100;
$balance=$AMOUNT;

# $payment=$PAYMENT;
$loop = 0;

while ($balance > 0 )
{
	if ( $loop < $payIndex )
	{
		$payment = @PAYMENT[$loop];
		++$loop;
	}

	$interest = roundUpAmount($rate * $balance);
	$principal = roundUpAmount($payment - $interest);
	if ( $balance < $principal )
	{
		$principal=$balance;
		$payment=$principal + $interest;
	}
	$balance=roundUpAmount($balance - $principal);
	print "$month\t\$$payment\t\$$interest\t\t\$$principal\t\t$\$balance\n";
	$month++;
}

sub roundUpAmount
{
	$value=$_[0];
	$newvalue=( int ( ( $value * 100 ) + .5 ) ) / 100;
	return ($newvalue);
}

2004.07.31

Vincenzo Maggio