Check if Number is Even or Odd in Go
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
Example 1: 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,
- Define a function named
checkEvenOdd
that takes one parametern
of typeint
. - Use an
if
statement to check if the number modulo 2 equals zero. If true, return "Even". - Use an
else
statement to handle the case where the number is not divisible by 2 and return "Odd". - 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