GO Program to search for array items

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

How to search items of array

Here an item is searched within the elements of the array. First we have to read the elements in the array. Then define which item is to be searched. Hold this item to be searched within a variable search. Traverse the array from the beginning and check whether the current item in the array is equal to the search item. If yes then print the position of the particular item in the array.

How to search items of array in the Go Program

Here we are showing how to search items of array in the Go language. Here variable Arr holds the array elements. Other variables size, search used as size of the array and search element. Use for loop for read the array elements. First, set flag with zero. Use for loop to find the index position of the element and iterate through the loop.

syntax for for loop


for    initializer; condition;   incrementor {
}

If (Arr[i] == search) then flag=0 means that searched element is find also take i as index position.

syntax for if condition


If condition {
//perform some instruction
}

Finally, check flag=0 if true we find the element otherwise not found. 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 search,size,flag,i

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

STEP 5: Search for the item in a for loop as  if (Arr[i] == search)

STEP 6: If matched set flag as flag = 0

STEP 7:Print the index position using fmt.Println()

 

GO Source Code

                                          package main
import "fmt"

func main() {
    var size, i, search 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("Enter the search item  = ")
    fmt.Scan(& search)
    flag := 0
    for i = 0; i < size; i++ {
        if Arr[i] == search {
            flag = 1
            break
        }
    }
    if flag == 1 {         
        fmt.Println("Search item ", search, " at position",i)
    } else {
        fmt.Println("Not found the search item ")
    }
}
                                      

OUTPUT

Enter the array Size = 5
Enter the array items  = 10 20 30 40 50
Enter the search item  = 40 Search item  40  at position 3