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

import java.util.Scanner;
class LinearSearch 
  public static void main(String args[])
    int c, n, search, array[];
    Scanner in = new Scanner(;
    System.out.println("Enter number of elements");
    n = in.nextInt(); 
    array = new int[n];
    System.out.println("Enter " + n + " integers");
    for (c = 0; c < n; c++)
      array[c] = in.nextInt();
    System.out.println("Enter value to find");
    search = in.nextInt();
    for (c = 0; c < n; c++)
      if (array[c] == search)     /* Searching element is present */
         System.out.println(search + " is present at location " + (c + 1) + ".");
   if (c == n)  /* Element to search is not present */
      System.out.println(search + " is not present in array.");

Download Linear Search Java program class file.

Output of program:
Linear Search Java program output

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.