to check if an element is present in the given list, we compare key element (search element) with every element in the list. If the number is found then display success otherwise the list doesn’t contain the element, that we are searching displays Search Unsuccessful.
import java.io.*;
public class LinearSearch{
public static void main(String args[]) throws IOException{
InputStreamReader read=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(read);
int a[]= new int[20];
int i, size, item, flag=0;
System.out.println(“Enter the size of the array:”);
size=Integer.parseInt(br.readLine());
System.out.println(“Enter the elements of the array:”);
for (i=0;i<size;i++){
a[i]=Integer.parseInt(br.readLine());
}
System.out.println(“Element to search:”);
item=Integer.parseInt(br.readLine());
for(i=0;i<size;i++){
if(item==a[i])
{
flag=1;
break;
} }
if(flag==1)
System.out.println(item+”found in position”+(i+1));
else
System.out.println(“Search Unsuccessful”);
}}
Output:
Enter the size of the array:
5
Enter the elements of the array:
45
25
41
42
56
Element to search:
41
41 found in position 3