Leap Year Checker in Go

 

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.

 

Leave a Reply

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