Go Program to Check Even or Odd Number

Introduction

Determining whether a number is even or odd is a fundamental operation in programming. An even number is divisible by 2 without a remainder, while an odd number has a remainder of 1 when divided by 2. This guide will show you how to write a Go program that checks whether a given number is even or odd.

Problem Statement

Create a Go program that:

  • Prompts the user to enter a number.
  • Checks whether the number is even or odd.
  • Displays the result.

Example:

  • Input: 7
  • Output: 7 is an odd number

Solution Steps

  1. Import the fmt Package: Use import "fmt" to include the fmt package for formatted I/O operations.
  2. Write the Main Function: Define the main function, which is the entry point of every Go program.
  3. Declare Variables: Declare a variable to store the number.
  4. Input the Number: Use fmt.Scanln to take input from the user for the number.
  5. Check Even or Odd: Use the modulus operator % to determine if the number is even or odd.
  6. Display the Result: Use fmt.Println to display whether the number is even or odd.

Go Program

package main

import "fmt"

/**
 * Go Program to Check Even or Odd Number
 * Author: https://www.javaguides.net/
 */
func main() {
    // Step 1: Declare a variable to hold the number
    var number int

    // Step 2: Prompt the user to enter a number
    fmt.Print("Enter a number: ")
    fmt.Scanln(&number)

    // Step 3: Check if the number is even or odd
    if number%2 == 0 {
        // Step 4: Display the result if the number is even
        fmt.Println(number, "is an even number")
    } else {
        // Step 5: Display the result if the number is odd
        fmt.Println(number, "is an odd number")
    }
}

Explanation

Step 1: Declare Variables

  • The variable number is declared as an integer to store the input number.

Step 2: Input the Number

  • The program prompts the user to enter a number using fmt.Print. The fmt.Scanln function reads the input and stores it in the number variable.

Step 3: Check Even or Odd

  • The modulus operator % is used to check if the number is even or odd. If number % 2 equals 0, the number is even; otherwise, it is odd.

Step 4 & 5: Display the Result

  • Depending on whether the number is even or odd, the program displays the appropriate message using fmt.Println.

Output Example

Example:

Enter a number: 7
7 is an odd number
Enter a number: 10
10 is an even number

Conclusion

This Go program demonstrates how to check whether a number is even or odd. It introduces basic concepts such as taking user input, using conditional statements, and performing arithmetic operations. This is a simple yet useful example for beginners learning Go programming.

Leave a Comment

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

Scroll to Top