This program uses a linear search algorithm to find a number from the N number.
/*Program : Linear Search Example * @author: Tech Cloud Classroom * Input: Number of elements, value per element, value to find data * Output: Location of number to find*/ImportJava.util.Scanner;classlinearsearchexample{ Public Static voidMain (String args[]) {intcounter, num, item, array[]; //capturing user inputScanner input =NewScanner (system.in); System.out.println ("Enter Number of elements:"); Num=Input.nextint (); //create an array to hold all integersArray =New int[num];
System.out.println ("Enter" + num + "integers"); //loop to store the number of user input in an 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 @ location" + (counter+1)); / * Find this number to stop the lookup and use break to terminate the For loop. */ Break; } } if(Counter = =num) SYSTEM.OUT.PRINTLN (Item+ "doesn ' t exist in array."); }}
Output 1:
Enter Number of elements:66 integers2233451399Enter The search value:4545 is Present at location 3
Output 2:
Enter Number of elements: 4 4 integers45Enter The search value: About doesn't exist in array.
Getting Started with Java: A linear search of basic algorithms