Odd or Even Number Checker in Go

 

 

Determine if a Number is Odd or Even in Go

This program takes an integer input from the user and determines whether the number is odd or even. The logic behind the program is quite simple: an even number is divisible by 2 without any remainder, whereas an odd number leaves a remainder of 1 when divided by 2.

Program Explanation

The program consists of the following main parts:

  1. Package Declaration: The program starts with the declaration of the main package.
  2. Importing Necessary Packages: The fmt package is imported to handle input and output operations.
  3. Main Function: The main function is the entry point of the program.
  4. Reading User Input: The program reads an integer input from the user.
  5. Determining Odd or Even: Using the modulus operator (%), the program checks whether the number is odd or even and prints the result.

Go Program

package main

import (
    "fmt"
)

func main() {
    var number int

    // Prompt the user for input
    fmt.Print("Enter an integer: ")
    fmt.Scan(&number)

    // Determine if the number is odd or even
    if number%2 == 0 {
        fmt.Println(number, "is even.")
    } else {
        fmt.Println(number, "is odd.")
    }
}

Explanation of Code

Let’s go through each part of the code:

  • package main: Declares the main package which is the starting point for any Go program.
  • import ("fmt"): Imports the fmt package to use its functions for input and output operations.
  • func main(): Defines the main function which is executed when the program runs.
  • var number int: Declares a variable number of type int to store the user input.
  • fmt.Print("Enter an integer: "): Prompts the user to enter an integer.
  • fmt.Scan(&number): Reads the user input and stores it in the number variable.
  • if number%2 == 0: Checks if the number is divisible by 2. If true, it means the number is even.
  • fmt.Println(number, "is even."): Prints that the number is even.
  • else: If the number is not divisible by 2, it is odd.
  • fmt.Println(number, "is odd."): Prints that the number is odd.

 

Leave a Reply

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