Scala program to calculate compound interest

1. Introduction

Compound interest is the interest on a loan or deposit that is calculated based on both the initial principal and the accumulated interest from previous periods. In this post, we'll explore a Scala program that calculates compound interest for a given principal, rate of interest, and number of years.

2. Program Steps

1. Set up the Scala environment.

2. Create an object to house the main function.

3. Define the principal amount, rate of interest, and number of years.

4. Implement a function to perform the compound interest calculation.

5. Invoke the function and display the result.

6. Execute the program.

3. Code Program

object CompoundInterestApp {
  def main(args: Array[String]): Unit = {
    // Define principal, rate of interest, and number of years
    val principal = 1000.0
    val rateOfInterest = 5.0  // in percentage
    val numberOfYears = 10
    val timesInterestAppliedPerYear = 4  // quarterly

    println(s"Calculating compound interest for principal: $$principal at rate: $rateOfInterest% for $numberOfYears years")

    // Calculate compound interest
    val compoundInterest = calculateCompoundInterest(principal, rateOfInterest, numberOfYears, timesInterestAppliedPerYear)
    println(s"\nCompound Interest: $$compoundInterest")
  }

  // Function to calculate compound interest
  def calculateCompoundInterest(principal: Double, rate: Double, years: Int, n: Int): Double = {
    val amount = principal * Math.pow(1 + (rate / (n * 100)), n * years)
    amount - principal  // Final interest is amount minus the principal
  }
}

Output:

Calculating compound interest for principal: $1000.0 at rate: 5.0% for 10 years
Compound Interest: $647.0094999811721

Explanation:

1. The program starts with an object named CompoundInterestApp. Inside this object, the main method serves as the entry point.

2. We declare the principal, rateOfInterest, numberOfYears, and timesInterestAppliedPerYear (quarterly, in this case).

3. A message is printed to show the parameters for the compound interest calculation.

4. The calculateCompoundInterest function is defined to handle the compound interest calculation. It uses the formula A = P(1 + r/n)^(nt) where A is the future value of the investment/loan, P is the principal investment/loan amount, r is the annual interest rate (in decimal), n is the number of times interest is applied per year, and t is the number of years.

5. Inside the main function, we invoke the calculateCompoundInterest method, retrieve the compound interest value, and display it.

6. The output displays the compound interest calculated for the defined principal, rate, and number of years.


Comments