Friday, December 14, 2018

Golang Example - Program to check Leap year or not

In this blog post, We will write a program to check a given a year  is a leap year or not
Leap year is a year which meets following conditions
  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 lear year which has 366 days
  5. This is not leap year  which has 365 days

Example program  to check given year is a leap year or not

The following features are used in go language
Following is 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)

}

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, so 1980 is a leap year
But 2011 is not divisible by 4, so 2001 is not leap year
Finally ,display the boolean value to console using Println() function

Related article


EmoticonEmoticon