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.

 

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 :)