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.
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.
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"
}
}
We can use the modulo operator to check if a number is even or odd.
For example,
checkEvenOdd
that takes one parameter n
of type int
.if
statement to check if the number modulo 2 equals zero. If true, return "Even".else
statement to handle the case where the number is not divisible by 2 and return "Odd".checkEvenOdd
function with sample numbers and print the results.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)
}
}
10 is Even 7 is Odd 4 is Even