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
- Import the fmt Package: Use import "fmt"to include the fmt package for formatted I/O operations.
- Write the Main Function: Define the mainfunction, which is the entry point of every Go program.
- Declare Variables: Declare a variable to store the number.
- Input the Number: Use fmt.Scanlnto take input from the user for the number.
- Check Even or Odd: Use the modulus operator %to determine if the number is even or odd.
- Display the Result: Use fmt.Printlnto 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 numberis 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. Thefmt.Scanlnfunction reads the input and stores it in thenumbervariable.
Step 3: Check Even or Odd
- The modulus operator %is used to check if the number is even or odd. Ifnumber % 2equals0, 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.