The preceding Java code implements linear search.
import java.util.Scanner;
class LinearSearch
{
public static void main(String args[])
{
int count, num, element, array[];
//To capture user input
Scanner input = new Scanner(System. in );
System.out.println("Enter number of elements in array:");
num = input.nextInt();
//Creating array to store the all the numbers
array = new int[num];
System.out.println("Enter " + num + " integers:");
//Loop to store each numbers in array
for (count = 0; count < num; count++)
array[count] = input.nextInt();
System.out.println("Enter the element to be searched:");
element = input.nextInt();
for (count = 0; count < num; count++)
{
if (array[count] == element)
{
System.out.println(element + " is present at location " + (count + 1));
/*Item is found so to stop the search and to come out of the
* loop use break statement.*/
break;
}
}
if (count == num)
System.out.println(element + " doesn't exist in array :(");
}
}Thank you, keep learning and sharing
