Print Updated Principal
In this step, you will learn how to track and print the updated principal balance after each loan payment, demonstrating the loan amortization process.
Open the previous loan_amortization.c
file and modify it to include multiple payment iterations:
cd ~/project
nano loan_amortization.c
Update the code to simulate multiple loan payments:
#include <stdio.h>
// Previous functions remain the same
double calculateMonthlyInterest(double principal, double annualRate) {
double monthlyRate = annualRate / 12 / 100;
return principal * monthlyRate;
}
double calculatePrincipalPortion(double payment, double monthlyInterest) {
return payment - monthlyInterest;
}
int main() {
double principal, rate, payment;
int totalPayments;
// Input loan details
printf("Enter the loan principal amount: ");
scanf("%lf", &principal);
printf("Enter the annual interest rate (in percentage): ");
scanf("%lf", &rate);
printf("Enter the monthly payment amount: ");
scanf("%lf", &payment);
printf("Enter the total number of payments: ");
scanf("%d", &totalPayments);
// Print initial loan details
printf("\nInitial Loan Details:\n");
printf("Principal: $%.2f\n", principal);
printf("Annual Interest Rate: %.2f%%\n", rate);
printf("Monthly Payment: $%.2f\n\n", payment);
// Simulate loan amortization
for (int month = 1; month <= totalPayments; month++) {
double monthlyInterest = calculateMonthlyInterest(principal, rate);
double principalPortion = calculatePrincipalPortion(payment, monthlyInterest);
// Update principal
principal -= principalPortion;
// Print monthly breakdown
printf("Payment %d:\n", month);
printf("Monthly Interest: $%.2f\n", monthlyInterest);
printf("Principal Portion: $%.2f\n", principalPortion);
printf("Remaining Principal: $%.2f\n\n", principal);
}
return 0;
}
Compile and run the updated program:
gcc loan_amortization.c -o loan_amortization
./loan_amortization
Example output:
Enter the loan principal amount: 10000
Enter the annual interest rate (in percentage): 5.5
Enter the monthly payment amount: 200
Enter the total number of payments: 3
Initial Loan Details:
Principal: $10000.00
Annual Interest Rate: 5.50%
Monthly Payment: $200.00
Payment 1:
Monthly Interest: $45.83
Principal Portion: $154.17
Remaining Principal: $9845.83
Payment 2:
Monthly Interest: $45.04
Principal Portion: $154.96
Remaining Principal: $9690.87
Payment 3:
Monthly Interest: $44.25
Principal Portion: $155.75
Remaining Principal: $9535.12