GO Program to print odd numbers in an array

For a better understanding of this example, we always recommend you to learn the basic topics of Golang programming listed below:

How to print odd numbers in an array

An integer is said to be odd if it is not a multiple of two or with a remainder greater than 0 when dividing with 2. For finding the odd numbers from the array elements first we have to read the elements into the array. Traverse the array from the beginning. Take each element from the array and perform a division with 2. If the element returns a reminder not equal to 0 then the number is odd. Continue the procedure with all the elements.

 

How to print odd numbers in an array using Go Program

Here we are showing how to print even numbers in an array in the Go language. Here variable Arr holds the array elements. Other variables size, i used as the size of the array and index for the loop. Use for loop to read the elements into the array. Again use another for loop to traverse the array to find the even numbers.

syntax for for loop


for    initializer; condition;   incrementor {
}

Within the for loop check If  if (Arr[i] %2!=0) then it is an odd number and print that number.

syntax for if condition


If condition {
//perform some instruction
}

Given below are the steps which are used in the Go program.

ALGORITHM

STEP 1: Import the package fmt

STEP 2: Start function main()

STEP 3: Declare the variable size,i

STEP 4: Read the array Arr[] using for loop

STEP 5: Search for the odd number in a for loop as  if (Arr[i] %2!=0)

STEP 6: If true it is an odd number otherwise continue the loop

STEP 7:Print the odd numbers using fmt.Println()

 

GO Source Code

                                          package main
import "fmt"

func main() {
    var size, i int
    fmt.Print("Enter the array size = ")
    fmt.Scan(& size)
    Arr := make([]int, size)
    fmt.Print("Enter the array items  = ")
    for i = 0; i < size; i++ {
        fmt.Scan(& Arr[i])
    }
    fmt.Print("\nThe list of odd numbers in Arr = ")
    for i = 0; i < size; i++ {
        if Arr[i]%2 != 0 {
            fmt.Print(Arr[i], " ")
        }
    }
    fmt.Println()
}
                                      

OUTPUT

Enter the array size = 10
Enter the array items  = 2 5 6 3 8 4 7 9 12 15

The list of odd numbers in Arr = 5 3 7 9 15