Sunday, February 19, 2017

Write a JAVA program to search for an element in a given list of elements using Linear search

import java.util.Scanner;

class LinearSearch
{
  public static void main(String args[])
  {
    int c, n, search, array[];
boolean status=false;

    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 */
      {
 status=true;
          break;
      }
   }
   if (status==true)
         System.out.println(search + " is present at location " + (c + 1) + ".");
else
      System.out.println(search + " is not present in array.");
  }
}
output:
>java LinearSearch
Enter number of elements
5
Enter 5 integers
12 14 15 17 19
Enter value to find
17

17 is present at location 4.

No comments:

Post a Comment

Write a JAVA program to sort an array of Strings

import java.util.Scanner; public class SortStrings {     public static void main(String[] args)     {         int n;         String t...