pTutorial

New way to learn Programming

Java program for linear

Java program to linear search or simple array search example. In linear search every array element compare with searched number. If integer is found then print index otherwise the array variable does not contains searching element.

Java linear search ecample

import java.util.Scanner;
public class JavaAraySearch 
{
  public static void main(String args[])
  {
    int k, n, temp, num[];
 
    Scanner in = new Scanner(System.in);
    System.out.println("Enter the array size");
    n = in.nextInt(); 
    num = new int[n];
 
    System.out.println("Enter " + n + " numbers");
 
    for (k = 0; k < n; k++)
      num[k] = in.nextInt();
 
    System.out.println("Enter integer to search");
    temp = in.nextInt();
 
    for (k = 0; k < n; k++)
    {
      if (num[k] == temp)     
      {
         System.out.println(temp + " is present at index " + (k + 1) + ".");
          break;
      }
   }
   if (k == n)  
      System.out.println(temp + " is not present in the array.");
  }
}

Output

Enter the array size
3
Enter 3 numbers
3
5
8
Enter integer to search
5
5 is present at index 2.

See Also


QUOTES OF THE DAY

Crafty men condemn studies, simple men admire them, and wise use them.

LIKE ON FACEBOOK

+1 ON GOOGLE

SHARE ON TWITTER