How to check Leap year or not in Golang with example
- Admin
- Dec 31, 2023
- Golang-examples
In this blog post, We will write a program to check whether a given year is a leap year or not.
How do you check if the year is a leap year or not?
- if the year is
divisible
by 4, check step 2, else go to step 5 - if the year is
divisible
by 100, check step 3 else go to step 4 - if the year is
divisible
by 400, check step 4, else go to step 5 - Then the year is
leap year
which has 366 days - This is not leap year which has 365 days
Finally, if the year meets all the above conditions, Then it is a Leap year
.
Example program to check given year is a leap year or not
go language provides the following features.
Following is an example code.
package main
import (
"fmt"
)
func isLeapYear(year int) bool {
leapFlag: = false
if year % 4 == 0 {
if year % 100 == 0 {
if year % 400 == 0 {
leapFlag = true
} else {
leapFlag = false
}
} else {
leapFlag = true
}
} else {
leapFlag = false
}
return leapFlag
}
func main() {
bool: = isLeapYear(1980)
bool1: = isLeapYear(2001)
fmt.Println(" 1980 leap year?:", bool)
fmt.Println(" 2001 leap year?:", bool1)
}
The above program is compiled and the output is
1980 leap year?: true
2001 leap year?: false
In the above program, Created a function isLeapYear
which accepts parameter year
of type int
and returns true
, if it is a leap year, else false
- if not leap year
Since 1980 is divisible by 4 and not divisible by 100, and 1980 is a leap year. But 2011 is not divisible by 4, so 2001 is not a leap year.
Finally,display the Boolean value to the console using the Println()
function.