Scala program to calculate leap years

1. Introduction

A leap year occurs nearly every 4 years to account for the solar year not being exactly 365.25 days long. To avoid decimal days, we add an extra day, February 29, almost every four years. However, the rule is more nuanced than just being a multiple of 4. In this post, we'll implement a Scala program to determine whether a given year is a leap year or not.

2. Program Steps

1. Initialize the Scala environment.

2. Define a function to check if a given year is a leap year.

3. Test the function with various year values.

4. Execute the program.

3. Code Program

object LeapYearCalculator {
  def main(args: Array[String]): Unit = {
    val years = List(2000, 1900, 2020, 2100, 2024)

    for (year <- years) {
      if (isLeapYear(year)) {
        println(s"$year is a leap year.")
      } else {
        println(s"$year is not a leap year.")
      }
    }
  }

  // Function to check if a year is a leap year
  def isLeapYear(year: Int): Boolean = {
    // If a year is multiple of 400, then it's a leap year
    if (year % 400 == 0) {
      true
    }
    // If a year is multiple of 100, then it's not a leap year
    else if (year % 100 == 0) {
      false
    }
    // If a year is multiple of 4, then it's a leap year
    else if (year % 4 == 0) {
      true
    }
    // Else it's not a leap year
    else {
      false
    }
  }
}

Output:

2000 is a leap year.
1900 is not a leap year.
2020 is a leap year.
2100 is not a leap year.
2024 is a leap year.

Explanation:

1. We start by defining an object LeapYearCalculator containing our main method and the isLeapYear function.

2. The isLeapYear function checks whether a year is a leap year using the following rules:

- If a year is divisible by 400, it is a leap year.

- If a year is divisible by 100 but not by 400, it is not a leap year.

- If a year is divisible by 4 but not by 100, it is a leap year.

- If none of the above conditions is met, it is not a leap year.

3. In the main method, we test the function with a list of year values, iterating over them and printing the result for each year.

4. The output section showcases the result of testing our function with five different years, highlighting the functionality of our leap year calculation.


Comments