ClearlyQ
ClearlyQ

Reputation: 31

Solving a C# interest problem, how do you calculate the number of years it takes a savings balance to reach its intended target balance?

Instructions

In this exercise you'll be working with savings accounts. Each year, the balance of your savings account is updated based on its interest rate. The interest rate your bank gives you depends on the amount of money in your account (its balance):

  • 3.213% for a negative balance.
  • 0.5% for a positive balance less than 1000 dollars.
  • 1.621% for a positive balance greater or equal than 1000 dollars and less than 5000 dollars.
  • 2.475% for a positive balance greater or equal than 5000 dollars.

You have three tasks, each of which will deal your balance and its interest rate.

I solved the first two tasks which asked for calculating the interest rate based on the specified balance and then calculating the annual balance update taking into account the interest rate.

The Third Task asks this:

Implement the (static) SavingsAccount.YearsBeforeDesiredBalance() method to calculate the minimum number of years required to reach the desired balance:

Example:

SavingsAccount.YearsBeforeDesiredBalance (balance: 200.75m, targetBalance: 214.88m)

Output// 14


My code so far for a balance over 5000 dollars:

public static int YearsBeforeDesiredBalance(decimal balance, decimal targetBalance)
{
    while ( balance <= targetBalance && targetBalance >5000 )
    {
        return  (int)((0.02475m * balance ) + balance);
        balance ++;
    }
}

I'm assuming I have to find a way to count the number of times this while loop executes, however I'm stuck on how to do it. Any guidance would be appreciated.

Upvotes: 3

Views: 1016

Answers (1)

Enigmativity
Enigmativity

Reputation: 117124

You have to leverage that you already have the following methods defined:

decimal CalculateTheInterestRateBasedOnTheSpecifiedBalance(decimal balance) { }
decimal CalculateTheAnnualBalanceUpdateTakingIntoAccountTheInterestRate(decimal balance, decimal interestRate) { }

Then it becomes easy:

public static int YearsBeforeDesiredBalance(decimal balance, decimal targetBalance)
{
    if (balance <= 0) throw new ArgumentOutOfRangeException("Balance cannot be less than or equal to zero.");
    if (targetBalance < 0) throw new ArgumentOutOfRangeException("Target Balance cannot be less than to zero."); /* Yes, only `<` */ 
    int years = 0;
    while (balance < targetBalance)
    {
        decimal interestRate = CalculateTheInterestRateBasedOnTheSpecifiedBalance(balance);
        balance = CalculateTheAnnualBalanceUpdateTakingIntoAccountTheInterestRate(balance, interestRate);
        years++;
    }
    return years;
}

Upvotes: 2

Related Questions