Go Program to print Odd and Even Numbers from an Array
We can print odd and even numbers from an array in Go by getting the remainder of each element and checking if it is divided by 2 or not. If it is divided by 2, it is an even number otherwise it is an odd number.
Example 1.
//Program to print odd & even numbers from an Arraypackage main
import "fmt"
// Main functionfunc main() {
numbers := [8]int{2, 11, 22, 5, 6, 3, 1, 9}
fmt.Println("Even Numbers:")
for i := 0; i < len(numbers); i++ {
if numbers[i]%2 == 0 { fmt.Println(numbers[i])
} }
fmt.Println("Odd Numbers:") for i := 0; i < len(numbers); i++ {
if numbers[i]%2 != 0 { fmt.Println(numbers[i])
} }}
Output:
Example 2. Using Slices
//Program to print odd & even numbers from an Arraypackage main
import "fmt"
// Main functionfunc main() {
numbers := [8]int{2, 11, 22, 5, 6, 3, 1, 9}
//a slice of unspecified size var oddnumbers []int var evennumbers []int
for i := 0; i < len(numbers); i++ {
if numbers[i]%2 == 0 {
evennumbers = append(evennumbers, numbers[i])
} else if numbers[i]%2 != 0 {
oddnumbers = append(oddnumbers, numbers[i])
} }
fmt.Println("Even Numbers:", evennumbers) fmt.Println("Odd Numbers:", oddnumbers)}