Go Tutorials

Go Programs

Go Check if Number is Even or Odd


Go Check if Number is Even or Odd

In this tutorial, we will learn how to check if a number is even or odd in Go. We will cover the basic conditional statements and the modulo operator to determine the parity of a number.


What is Even and Odd Number Checking

Even and odd number checking is the process of determining whether a number is divisible by 2. An even number is completely divisible by 2, whereas an odd number leaves a remainder of 1 when divided by 2.


Syntax

The syntax to check if a number is even or odd in Go is:

func checkEvenOdd(n int) string {
    if n % 2 == 0 {
        return "Even"
    } else {
        return "Odd"
    }
}


Youtube Learning Video



Checking if a number is even or odd

We can use the modulo operator to check if a number is even or odd.

For example,

  1. Define a function named checkEvenOdd that takes one parameter n of type int.
  2. Use an if statement to check if the number modulo 2 equals zero. If true, return "Even".
  3. Use an else statement to handle the case where the number is not divisible by 2 and return "Odd".
  4. In the main function, call the checkEvenOdd function with sample numbers and print the results.

Go Program

package main

import (
    "fmt"
)

func checkEvenOdd(n int) string {
    if n % 2 == 0 {
        return "Even"
    } else {
        return "Odd"
    }
}

func main() {
    // Sample numbers
    numbers := []int{10, 7, 4}

    // Check and print if each number is even or odd
    for _, number := range numbers {
        result := checkEvenOdd(number)
        fmt.Printf("%d is %s\n", number, result)
    }
}

Output

10 is Even
7 is Odd
4 is Even