Linear Search Program in Java

In this example, You learn about java program for Linear Search. 

Here you learn linear search in Java, You are given an array, also number to find in the present array and the task of the program to find number in array.

Linear Search Program in Java

import java.util.Scanner;
public class LinearSearch
{
 public static void main(String args[])
 {
    int c, n, search, array[];
    Scanner in = new Scanner(System.in);
    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) +".");
            break;
        } 
    }
    if (c == n) /* Searching element is absent */
        System.out.println(search + " is not present in array.");
 }
}
Output

Enter number of elements
4

Enter 4 integers
1 2 3 5

Enter value to find
5

5 is present at location 4.

If you have any doubts, Please let me know

Previous Post Next Post

Contact Form