Linear search program in Java

Linear search is one of the basic searching techniques used in programming. There are many other advanced techniques for searching, but to learn about searching we shoudl start with linear search. This technique is simple to learn, among all the given integers, we should match our search element and if found we shall display appropriate message.

Starting from the first element of the array we need to check each and every element with the search key element. If element does not match, it moves to the next element and checks it.

import java.util.*;

public class linearsearch{
		public static void main(String args[]){

			Scanner in = new Scanner(;
			int counter;
			System.out.println("\nEnter the size of the array:");
			int size = in.nextInt();
			float[] data = new float[size];
			for(int i=0;i<size;i++){
				System.out.println("\nEnter element into the array:");
				data[i] = in.nextFloat();
			System.out.println("\nEnter element you need to search:");
			float key = in.nextFloat();
			counter = 0;
			for(int i=0;i<size;i++){
				if(data[i] == key){
						System.out.println("\nKey element" + key +"is in the given array");
				counter++; //Incremented to check for element found or not.
			if(counter == size )
					System.out.println("\nElement not found");


Download the source code

This entry was posted in Java and tagged , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s