{

Golang Example - Program to check Leap year or not


Golang Program to check Leap year

In this blog post, We will write a program to check a given year is a leap year or not.

How do you check if the year is a leap year or not?

  1. if the year is divisible by 4, check step 2, else go to step 5
  2. if the year is divisible by 100, check step 3 else go to step 4
  3. if the year is divisible by 400, check step 4, else go to step 5
  4. Then the year is leap year which has 366 days
  5. This is not leap year which has 365 days

Finally, if the year meets all the above conditions, Then it is 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 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 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 console using Println() function

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.