Write a program to Search an item into the array using linear search


The linear_search method takes an array of integers a and an integer item as parameters. It uses a loop to iterate through the array and check if the current element is equal to item. If a match is found, the method returns the index of the matching element. If no match is found, it returns -1.

In the main method, the program prompts the user to input the elements of the array a. It then prompts the user to input the item to be searched. It calls the linear_search method with the array a and the item to be searched. If the returned index is -1, it means the item was not found, so the program prints "Item Not Found". Otherwise, it prints "Item Found at Index pos", where pos is the index returned by the linear_search method.

Source Code

import java.util.Scanner;
public class Linear_Search
{
	static int linear_search(int a[], int item)
	{
		int cnt = 0;
		int pos = -1;
 
		for (cnt = 0; cnt < a.length; cnt++)
		{
			if (a[cnt] == item)
			{
				pos = cnt;
				break;
			}
		}
		return pos;
	}
 
	public static void main(String[] args)
	{
		Scanner input = new Scanner(System.in);
		int i = 0;
		int n = 0;
		int a[] = new int[5];
 
		int item = 0;
		int pos = 0;
 
		for (i = 0; i < a.length; i++)
		{
			System.out.printf("Enter Array Elements a[%d] : ",i);
			a[i] = input.nextInt();
		}
 
		System.out.printf("Enter Item to Search : ");
		item = input.nextInt();
 
		pos = linear_search(a, item);
 
		if (pos == -1)
		System.out.printf("Item Not Found");
		else
		System.out.printf("Item Found at Index %d", pos);
	}
}

Output

Enter Array Elements a[0] : 10
Enter Array Elements a[1] : 20
Enter Array Elements a[2] : 30
Enter Array Elements a[3] : 56
Enter Array Elements a[4] : 84
Enter Item to Search : 30
Item Found at Index 2

Example Programs