Menu Close

Go – Program to find a number which occurs odd number of times in an array of integers in go golang.

In this article, we are going to learn to find a number which occurs odd number of times in an array of integers in go golang.

Here, only one number will have odd number of count in array.

Examples:

 Input: arr = [1, 2, 3, 1, 2, 3, 2]

Output: 2

Explanation: 2 occurs 3 times in an array.


Input: arr = [1, 2, 3, 1, 2, 3]

Output: 0

Explanation: None number occurs odd time.

Note: XOR (^) of two same number becomes zero i.e 2 ^ 2 = 0.

Algorithm:

  • Get the size of array from user
  • Insert the number into array
  • Apply XOR (^) operator to all numbers
  • All even time occurred numbers will become zero. Only odd time occurred number will remain same.
package main

import "fmt"

func check_odd_element(arr []int) {

    length := len(arr)

    var odd_number int = arr[0]

    for i := 1; i < length; i++ {
        
        // Perform XOR (^) operator to all elements in array
        odd_number = odd_number ^ arr[i]
        
    }
    
    fmt.Printf("\nOdd number occurance is: %d", odd_number)
}

func main() {

    var size, number int

    fmt.Print("Enter the size of array: ")

    // Get the array size from user
    fmt.Scan(&size)

    arr := make([]int, size)

    for i := 0; i < size; i++ {

        fmt.Print("\nEnter the number: ")
        fmt.Scan(&number)

        // Fill the elements into array
        arr[i] = number
    }
    check_odd_element(arr)
}

Output:

Enter the size of array: 5
Enter the number: 1
Enter the number: 2
Enter the number: 3
Enter the number: 1
Enter the number: 2
Odd number occurance is: 3

Enter the size of array: 6
Enter the number: 1
Enter the number: 2
Enter the number: 3
Enter the number: 1
Enter the number: 2
Enter the number: 3
0

To learn more about golang, Please refer given below link:

https://techieindoor.com/go-lang-tutorial/
https://techieindoor.com/go-lang-tutorial/

References:

 https://golang.org/doc/
https://golang.org/pkg/
https://golang.org/pkg/fmt/
https://golang.org/pkg/fmt/#Println
Posted in golang, golang program

Leave a Reply

Your email address will not be published. Required fields are marked *