Leap Year Checker in Go

This document provides a Go program to determine if a given year is a leap year. The program includes an explanation of the structure and documentation.

Program Code


package main

import (
    "fmt"
)

// isLeapYear function determines if a given year is a leap year.
func isLeapYear(year int) bool {
    // Leap year is divisible by 4
    // However, if divisible by 100, it must also be divisible by 400
    if year%400 == 0 {
        return true
    } else if year%100 == 0 {
        return false
    } else if year%4 == 0 {
        return true
    }
    return false
}

func main() {
    var year int
    fmt.Print("Enter a year: ")
    fmt.Scan(&year)
    
    if isLeapYear(year) {
        fmt.Printf("%d is a leap year.\n", year)
    } else {
        fmt.Printf("%d is not a leap year.\n", year)
    }
}
    

Program Explanation

The program is structured as follows:

  1. Importing Packages:The program imports the fmt package, which provides I/O functions for formatting and scanning input/output.
  2. Defining the isLeapYear Function:The isLeapYear function determines if a year is a leap year. The function accepts an integer parameter year and returns a boolean value:
    • If the year is divisible by 400, it is a leap year.
    • If the year is divisible by 100 but not by 400, it is not a leap year.
    • If the year is divisible by 4 but not by 100, it is a leap year.
    • If none of the above conditions are met, it is not a leap year.
  3. The main Function:The main function is the entry point of the program:
    • It prompts the user to enter a year.
    • It reads the year using fmt.Scan.
    • It calls the isLeapYear function to check if the year is a leap year.
    • It prints the result using fmt.Printf.

Documentation

The program is documented to provide clarity on its functionality:

  • Package: main – The main package is used for standalone programs in Go.
  • Function: isLeapYear – Determines if the provided year is a leap year.
  • Function: main – The program’s entry point where user interaction and output occur.

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

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

error

Enjoy this blog? Please spread the word :)