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 Array
package main

import "fmt"

// Main function
func 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 Array
package main

import "fmt"

// Main function
func 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)
}

Output:

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Spring boot video streaming example-HTML5

Spring Boot + Mockito simple application with 100% code coverage

Spring Boot + OpenCSV Export Data to CSV Example

Custom Exception Handling in Quarkus REST API

Registration and Login with Spring Boot + Spring Security + Thymeleaf

DataTable-Pagination example with Spring boot, jQuery and ajax

Spring Webflux File Download - REST API Example

Node JS mini projects with source code - free download

ReactJS, Spring Boot JWT Authentication Example