You are here

Java program for linear search

Java program for linear search: Linear search is very simple, to check if an element is present in the given list we compare it with every element in the list. If it is found then we print the location at which it occurs, otherwise the list doesn't contain the element we are searching.

Java programming code

  1.    
  2. import java.util.Scanner;
  3.  
  4. class LinearSearch
  5. {
  6.   public static void main(String args[])
  7.   {
  8.     int c, n, search, array[];
  9.  
  10.     Scanner in = new Scanner(System.in);
  11.     System.out.println("Enter number of elements");
  12.     n = in.nextInt();
  13.     array = new int[n];
  14.  
  15.     System.out.println("Enter " + n + " integers");
  16.  
  17.     for (c = 0; c < n; c++)
  18.       array[c] = in.nextInt();
  19.  
  20.     System.out.println("Enter value to find");
  21.     search = in.nextInt();
  22.    
  23.     for (c = 0; c < n; c++)
  24.     {
  25.       if (array[c] == search)     /* Searching element is present */
  26.       {
  27.          System.out.println(search + " is present at location " + (c + 1) + ".");
  28.           break;
  29.       }
  30.    }
  31.    if (c == n)  /* Element to search isn't present */
  32.       System.out.println(search + " isn't present in array.");
  33.   }
  34. }

Output of program:
Linear Search Java program output

Download Linear Search Java program class file.

The program finds the first instance of an element to search, you can modify it for multiple occurrences of the same element and count how many times it occurs in the list. Similarly, you can find if an alphabet is present in a string.