MATLAB: While loop for loan repayment

homeworkloanswhile loop

In the picture shown, I have to basically create each loan payment table underneath its respective black line. Although I was able to create the first two tables, I am having trouble with two things: The first is finding the "Sum of Interest Paid" and "Sum of Payments" at the bottom of each table; the second problem is actually creating the third table. Any assistance would be appreciated. Here is my code:
InitialBalance = input('Enter the initial balance in US$ : '); % 10,000,3000,9000
% if initial balance is more than or equal to 5000, then interest rate is
% 2%. Anything else is 1%
if InitialBalance>=5000
rate=0.02;
fprintf('\nYour minimum monthly payment is $%g\n',rate*InitialBalance+1)
Minimum=rate*InitialBalance+1;
else
rate=0.01;
fprintf('\nYour minimum monthly payment is $%g\n',rate*InitialBalance+1)
Minimum=rate*InitialBalance+1;
end
MonthPay = input('Enter the Monthly Payment in US$ : '); % 12000, 4000, 2000
month=0; % initialize months
Payment=0; % initialize payment
Interest=0;
fprintf('\nMonths \t Interest($) \t Payment($) Balance($)\n')
fprintf(' %2i %2i %2i %2i\n',month,Interest,Payment,InitialBalance)
Balance=InitialBalance;
while MonthPay>=Minimum % initiates while loop if and only if monthly payment >= minimum payment
while Balance~=0
month=month+1;
Payment=MonthPay;
Interest=rate*Balance;
Payment=Interest+Balance;
if Balance-Payment<0
Balance=0;
else
Balance=Balance-Payment;
end
fprintf(' %2i %2i %2i %2i\n',month,Interest,Payment,Balance)
end
end
fprintf('\nSum of Interest Paid = $%b\n')
fprintf('\tSum of Payments = $%b')

Best Answer

Your final two fprintf()'s don't have any numerical values to be put into the %b. You need to have a variable sumOfPayments and sumOfInterest and increment that inside the loop by the payment and interest for that iteration, after you've initialized it to zero before the loop of course.
And I wouldn't use %i and %b. b is not even anything. I would use %d for integers and %.2 for fractional real numbers.
Related Question