Print the Payment
In this final step, we'll enhance our mortgage calculator to provide a detailed payment breakdown and format the output for better readability.
Let's modify the mortgage_calculator.c
file to add more comprehensive payment information:
cd ~/project
nano mortgage_calculator.c
Update the code with improved payment printing:
#include <stdio.h>
#include <math.h>
double calculate_mortgage_payment(double principal, double rate, int num_payments) {
// Monthly interest rate
double monthly_rate = rate / 12;
// Calculate payment using the mortgage formula
double payment = principal *
(monthly_rate * pow(1 + monthly_rate, num_payments)) /
(pow(1 + monthly_rate, num_payments) - 1);
return payment;
}
void print_payment_details(double principal, double rate, int num_payments, double monthly_payment) {
double total_payment = monthly_payment * num_payments;
double total_interest = total_payment - principal;
printf("\n--- Mortgage Payment Breakdown ---\n");
printf("Loan Principal: $%10.2f\n", principal);
printf("Annual Interest Rate: %10.2f%%\n", rate * 100);
printf("Total Number of Payments: %d\n", num_payments);
printf("Monthly Payment: $%10.2f\n", monthly_payment);
printf("Total Payments: $%10.2f\n", total_payment);
printf("Total Interest Paid: $%10.2f\n", total_interest);
}
int main() {
double principal, rate;
int num_payments;
// Prompt and read principal amount
printf("Enter the loan principal amount: ");
scanf("%lf", &principal);
// Prompt and read annual interest rate
printf("Enter the annual interest rate (as a decimal): ");
scanf("%lf", &rate);
// Prompt and read number of payments
printf("Enter the total number of payments: ");
scanf("%d", &num_payments);
// Calculate monthly payment
double monthly_payment = calculate_mortgage_payment(principal, rate, num_payments);
// Print detailed payment information
print_payment_details(principal, rate, num_payments, monthly_payment);
return 0;
}
Compile the program:
gcc mortgage_calculator.c -o mortgage_calculator -lm
Run the program:
./mortgage_calculator
Example output:
Enter the loan principal amount: 200000
Enter the annual interest rate (as a decimal): 0.05
Enter the total number of payments: 360
--- Mortgage Payment Breakdown ---
Loan Principal: $ 200000.00
Annual Interest Rate: 5.00%
Total Number of Payments: 360
Monthly Payment: $ 1073.64
Total Payments: $ 386510.40
Total Interest Paid: $ 186510.40
Key improvements:
- Added a new function
print_payment_details()
for formatted output
- Calculate total payments and total interest
- Use formatting to align decimal values
- Provide a clear, readable breakdown of mortgage details