Q:

Golang program to search an item in the array using linear search

belongs to collection: Golang Array Programs

0

In this program, we will create an integer array and read elements from the user. Then we will search the given item in the array and print the appropriate message on the console screen.

Linear Search: Linear search is also known as sequential search, in the sequential search, we search items by comparing each element one by one.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program/Source Code:

The source code to search an item in the array using linear search is given below. The given program is compiled and executed successfully.

// Golang program to search an item in the array
// using linear search

package main

import "fmt"

func main() {
	var arr [5]int
	var item int = 0
	var flag int = 0
	fmt.Printf("Enter array elements: \n")
	for i := 0; i <= 4; i++ {
		fmt.Printf("Elements: arr[%d]: ", i)
		fmt.Scanf("%d", &arr[i])
	}

	fmt.Printf("Enter item: ")
	fmt.Scanf("%d", &item)
	for i := 0; i <= 4; i++ {
		if item == arr[i] {
			flag = 1
			fmt.Printf("Item %d at index %d", item, i)
			break
		}
	}

	if flag == 0 {
		fmt.Printf("Item %d not found in array")
	}
}

Output:

Enter array elements:
Elements: arr[0]: 11
Elements: arr[1]: 22
Elements: arr[2]: 33
Elements: arr[3]: 44
Elements: arr[4]: 55
Enter item: 33
Item 33 at index 2

Explanation:

In the above program, we declare the package main. The main package is used to tell the Go language compiler that the package must be compiled and produced the executable file. Here, we imported the fmt package that includes the files of package fmt then we can use a function related to the fmt package.

In the main() function, we created an array arr and read elements from the user. Then we searched items in an array using linear or sequential search. After that, we printed the appropriate message on the console screen.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Golang Array Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Golang program to search an item in the array usin... >>
<< Golang program to print the prime numbers from an ...