How to write a program to find if given year is leap year in Go Language

neotam Avatar

How to write a program to find if given year is leap year in Go Language
Posted on :

Tags :

A leap year is the year which divisible by 4. But all century(multiples of 100) years that are divisible 4 are not leap years, in such a case it is tested against if it is divisible by 400.

Here is the simple program that will check if given year is leap year or not

At very first given year is checked if it is divisible by 4 if so it might be leap year else it is not leap year. Control flow enters into the if block if given year is divisible by 4, inside if block given year is checked against if it is the century year, if it not a century year it is a leap year. If given year is century year then it must be divisible by 400 to be a leap year.

Following code leverages the syntax of go to make it simple by using switch with out expression syntax in which each case statement will use condition much like if. Code of case block will be executed if expression evaluates true

Leap year program can be further compacted by using logical and, logical or operators as follows

package main

import "fmt"

func main() {
	var n int
	fmt.Printf("Enter year: ")
	fmt.Scanf("%d", &n)

	if (n%4 == 0 && n%100 != 0) || (n%4 == 0 && n%100 == 0 && n%400 == 0) {
		fmt.Println("It is leap year")
	} else {
		fmt.Println("It is not leap year")


Assuming code is save in a file checkleapyear.go . Run the code using following command

go run checkleapyear.go

Leave a Reply

Your email address will not be published. Required fields are marked *