public double Loan { get; set; }
public double Rate { get; set; }
public int Term { get; set; }
private double _totalCost;
private double _totalInterest;
public Mortgage(double loan, double rate, int term)
if (_payment == 0) _payment = CalcPayment(Loan, Rate, Term);
if (_totalCost == 0) _totalCost = CalcTotalCost(Payment, Term);
public double TotalInterest
if (_totalInterest == 0) _totalInterest = CalcTotalInterest(TotalCost, Loan);
private double CalcPayment(double principal, double annualRate, int months)
double monthlyRate = (annualRate / 100) / 12;
return principal * (monthlyRate * Math.Pow(1 + monthlyRate, months)) / (Math.Pow(1 + monthlyRate, months) - 1);
private double CalcTotalCost(double payment, int months)
private double CalcTotalInterest(double cost, double principal)
public override string ToString()
return string.Format("{0,10:C2} {1,6:F2} % {2,8} {3,10:C2} {4,14:C2} {5,12:C2}",
Loan, Rate, Term, Payment, TotalCost, TotalInterest);
public static void Main()
Console.WriteLine("How many mortgage products would you like to compare? (0 to 10)");
if (int.TryParse(Console.ReadLine(), out numProducts) && numProducts > 0 && numProducts <= 10)
Mortgage[] mortgages = new Mortgage[numProducts];
for (int i = 0; i < numProducts; i++)
Console.WriteLine("\nMortgage Product #{0}", i + 1);
Console.WriteLine("Loan $ (10000 <= range <= 1000000) : ");
double loan = PromptForValue(10000, 1000000);
Console.WriteLine("Rate % (0.1 <= range <= 25) : ");
double rate = PromptForValue(0.1, 25);
Console.WriteLine("Term mo (60 <= range <= 360) : ");
int term = (int)PromptForIntValue(60, 360);
mortgages[i] = new Mortgage(loan, rate, term);
Console.WriteLine("\n{0,10} {1,8} {2,8} {3,10} {4,14} {5,12}", "Loan", "Rate", "Months", "Payment", "Total Cost", "Interest");
Console.WriteLine("========== ======== ======== ========== ============== ============");
for (int i = 0; i < numProducts; i++)
Console.WriteLine(mortgages[i]);
Console.WriteLine("Invalid number of products.");
static double PromptForValue(double min, double max)
if (double.TryParse(Console.ReadLine(), out value) && value >= min && value <= max)
Console.WriteLine("Invalid input. Please enter a value between {0} and {1}.", min, max);
static int PromptForIntValue(int min, int max)
if (int.TryParse(Console.ReadLine(), out value) && value >= min && value <= max)
Console.WriteLine("Invalid input. Please enter a value between {0} and {1}.", min, max);