begincoding123 - 5 months ago 34

C Question

I am trying to create a C program which calculates the monthly payment and print a table of payment schedule for a fixed rate loan. My issue is that the loop only iterates once but I cannot figure out why. Here is how the output should looked like:

`#include <stdio.h>`

#include <math.h>

double calculatePayments(double loan, double rate, int payment);

int main(){

double loan,rate,monthly,principal,interest,balance;

int payment, counter;

counter = 0;

balance = 0.0;

printf("Enter amount of loan: ");

scanf("%lf", &loan);

printf("Enter interest rate per year:%% ");

scanf("%lf", &rate);

printf("Enter number of payments: ");

scanf("%d", &payment);

monthly = calculatePayments(loan, rate, payment);

printf("Monthly payment should be %.2f\n", monthly);

printf("—————AMORTIZATION SCHEDULE—————\n ");

printf("N\tPayment\tPrincipal\tInterest\tBalance\n ");

do{

rate = rate/12/100;

interest = loan * rate;

principal = monthly - interest;

balance = loan - principal;

counter++;

printf("%d\t%.2f\t%.2f\t\t%.2f\t\t%.2f\n", counter, monthly, principal, interest, balance);

}while(balance < 0);

return 0;

}

double calculatePayments(double loan, double rate, int payment) {

rate = rate/12/100;

double mul = pow(1+rate, payment);

return (loan * mul * rate) / (mul - 1);

}

Answer

Changing up the do ... while loop

```
// e.g. 7.5/12/100 = 0.00625
rate = rate/12/100;
do{
// e.g. 500*0.00625=3.125
interest = loan * rate;
// e.g. 101.88-3.125=98.76
principal = monthly - interest;
// e.g. 500-98.76=401.24
balance = loan - principal;
// update loan
loan = balance;
counter++;
printf("%d\t%.2f\t%.2f\t\t%.2f\t\t%.2f\n", counter, monthly, principal, interest, balance);
}while(balance > principal);
```