Determine Odd or Even Number in Go

 

Introduction

In this program, we will determine whether a given number is odd or even.
An even number is divisible by 2, meaning it has no remainder when divided by 2.
An odd number leaves a remainder of 1 when divided by 2.
This program is a simple example to demonstrate basic conditional logic in the Go programming language.

Objective

The objective of this program is to take an integer input from the user,
check whether the number is odd or even, and print the result to the screen.
The program will utilize basic control flow in Go, particularly the if-else statement.

Go Code


package main

import "fmt"

func main() {
    // Declare a variable to store the user's input
    var number int
    
    // Prompt the user for input
    fmt.Print("Enter a number: ")
    
    // Read the input from the user
    fmt.Scanln(&number)
    
    // Check if the number is divisible by 2 (even)
    if number % 2 == 0 {
        fmt.Println(number, "is even.")
    } else {
        fmt.Println(number, "is odd.")
    }
}
        

Explanation of the Program Structure

This Go program works as follows:

  • Importing Packages: The program starts by importing the fmt package, which is required to handle input and output operations.
  • Declaring a Variable: We declare a variable number of type int to store the user’s input.
  • Reading Input: Using the fmt.Scanln() function, we read an integer input from the user and store it in the number variable.
  • Conditional Check: The if statement checks if the number is divisible by 2. If the remainder is 0 (i.e., number % 2 == 0), the number is even, otherwise, it is odd.
  • Output: Based on the result of the conditional check, the program prints whether the number is even or odd using fmt.Println().

How to Run the Program

    1. Install Go: Make sure you have Go installed on your system. You can download it from the official website: https://golang.org/dl/.
    2. Save the Code: Copy the provided code into a text file and save it with a .go extension, for example, odd_even.go.
    3. Run the Program: Open your terminal or command prompt, navigate to the directory where the odd_even.go file is saved, and run the following command:
go run odd_even.go
  1. Input a Number: The program will prompt you to enter a number. After you input a number and press Enter, the program will tell you whether the number is odd or even.

Example Output

        Enter a number: 15
        15 is odd.

 

One Reply to “Determine Odd or Even Number in Go”

Leave a Reply

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