Check Leap Year in Go



In this tutorial, we will learn how to check if a year is a leap year in Go. We will cover the basic rules for determining leap years and implement a function to perform the check.


What is a Leap Year

A leap year is a year that is divisible by 4, but not by 100, unless it is also divisible by 400. This ensures that the year has an extra day, February 29, to keep the calendar year synchronized with the astronomical year.


Syntax

The syntax to check if a year is a leap year in Go is:

func isLeapYear(year int) bool {
    if year%4 == 0 {
        if year%100 == 0 {
            if year%400 == 0 {
                return true
            }
            return false
        }
        return true
    }
    return false
}


Example 1: Checking if a year is a leap year

We can create a function to check if a given year is a leap year based on the leap year rules.

For example,

  1. Define a function named isLeapYear that takes one parameter year of type int.
  2. Use nested if statements to check the divisibility rules for leap years.
  3. Return true if the year is a leap year, otherwise return false.
  4. In the main function, call the isLeapYear function with sample years and print the results.

Go Program

package main

import (
    "fmt"
)

func isLeapYear(year int) bool {
    if year%4 == 0 {
        if year%100 == 0 {
            if year%400 == 0 {
                return true
            }
            return false
        }
        return true
    }
    return false
}

func main() {
    // Sample years
    years := []int{2020, 1900, 2000, 2021}

    // Check and print if each year is a leap year
    for _, year := range years {
        result := isLeapYear(year)
        if result {
            fmt.Printf("%d is a leap year\n", year)
        } else {
            fmt.Printf("%d is not a leap year\n", year)
        }
    }
}

Output

2020 is a leap year
1900 is not a leap year
2000 is a leap year
2021 is not a leap year