Computer Science, asked by justheretocopy, 9 months ago

Computer [Array]
Accept numbers into an array of size 10. Then accept a number from the user and perform linear search of that number in the array. If the number is present in the array, then display the array element number where number is found. In case of multiple presence of the element, display all the positions. Display a proper message if the number is not present in the array.

Answers

Answered by Aishwarya98
3

import java.util.Scanner;

class LinearSearchExample

{

  public static void main(String args[])

  {

     int counter, num, item, array[];

     //To capture user input

     Scanner input = new Scanner(System.in);

     System.out.println("Enter number of elements:");

     num = input.nextInt();  

     //Creating array to store the all the numbers

     array = new int[num];  

     System.out.println("Enter " + num + " integers");

     //Loop to store each numbers in array

     for (counter = 0; counter < num; counter++)

       array[counter] = input.nextInt();

     System.out.println("Enter the search value:");

     item = input.nextInt();

     for (counter = 0; counter < num; counter++)

     {

        if (array[counter] == item)  

        {

          System.out.println(item+" is present at location "+(counter+1));

          /*Item is found so to stop the search and to come out of the  

           * loop use break statement.*/

          break;

        }

     }

     if (counter == num)

       System.out.println(item + " doesn't exist in array.");

  }

}

Sample Input and Output:

Enter number of elements:

6

Enter 6 integers

22

33

45

1

3

99

Enter the search value:

45

45 is present at location 3

Similar questions