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.
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.
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
}
We can create a function to check if a given year is a leap year based on the leap year rules.
For example,
isLeapYear
that takes one parameter year
of type int
.if
statements to check the divisibility rules for leap years.true
if the year is a leap year, otherwise return false
.isLeapYear
function with sample years and print the results.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)
}
}
}
2020 is a leap year 1900 is not a leap year 2000 is a leap year 2021 is not a leap year