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

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Spring Boot + Mockito simple application with 100% code coverage

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete