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.*; import java.io.*; public class linearsearch{ public static void main(String args[]){ Scanner in = new Scanner(System.in); 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"); System.exit(0); } counter++; //Incremented to check for element found or not. } if(counter == size ) System.out.println("\nElement not found"); } }