/Searching an Element in Array

Searching an Element in Array

Searching an element in array is very easy, we just need to iterate through every element in the array and if we find the element just prints its location otherwise just print “the element not found”.

This type of searching is basically called “Linear Searching ” or “Sequential Searching” because we are  searching for the element in a sequential manner.

Example :

import java.util.Scanner;
public class LinearSearch {
public static void main(String args[])
{
Scanner scanner=new Scanner(System.in);
System.out.println("Enter the size of Array ");
int arraysize=scanner.nextInt();
System.out.println("Enter the elements ");
int a[]=new int[arraysize];
for(int i=0;i<a.length;i++)
{
a[i]=scanner.nextInt();
}

System.out.println("Enter the element to be searched");
int element=scanner.nextInt();

boolean ispresent=false;
for(int i=0;i<a.length;i++)
{
if(a[i]==element)
{
ispresent=true;
System.out.println("Element found at "+(i+1));
break;
}
}
if(!ispresent)
{
System.out.println("Sorry! Element Not Found");
}
}
}