Sequential Search Program

  • Sequential search is also called as Linear search.
  • It checks every one of its elements one by one in sequence, until desired element is not found.
Create new java project using eclipse as follows
  • Write the code for sequential search as follows in the class
  • package com.search.sequentialSearch;
    
    					import java.util.Scanner;
    
    					public class SequentialSearchImpl {
    	
    					public static void main(String[] args) {
    		
    					int counter, numberOfElements, item, array[];
    		
    					//To get the user input
    					Scanner input = new Scanner(System.in);
    					System.out.println("Enter number of elements:");
    					numberOfElements = input.nextInt();
    	      
    					//Creating array to store the user entered elements
    					array = new int[numberOfElements]; 
    					System.out.println("Enter " + numberOfElements + " integers");
    	      
    					//Loop to store each number in array
    					for (counter = 0; counter < numberOfElements; counter++)
    					array[counter] = input.nextInt();
    
    					System.out.println("Enter the search value:");
    					item = input.nextInt();
    
    					for (counter = 0; counter < numberOfElements; counter++)
    					{
    					if (array[counter] == item) 
    					{
    					System.out.println(item+" is present at location "+(counter+1));
    	           
    					/*Item is found so, to come out of the loop*/
    					break;
    					}
    					}
    					if (counter == numberOfElements)
    					System.out.println(item + " doesn't exist in array.");
    					}
    					}
  • Create main class to run the immutable class write code as follows
  • Now run your program as Java Application
  • Enter the total number of elements on console
  • Enter the integer numbers
  • Enter the elements you want to search and you should get output as follows