Define a class to accept values into an array of double data type of size 20. Accept a double value from the user and search in the array using the linear search method. If the value is found display the message "Found" with its position where it is present in the array. Otherwise display the message "not found".
Topic: Linear search on a double array
Answer
import java.util.Scanner;
class LinearSearchD { public static void main(String args[]) { Scanner sc = new Scanner(System.in); double a[] = new double[20]; int pos = -1;
System.out.println("Enter 20 double values :"); for(int i = 0; i < 20; i++) a[i] = sc.nextDouble();
System.out.print("Enter the value to search : "); double key = sc.nextDouble();
for(int i = 0; i < 20; i++) { if(a[i] == key) { pos = i; break; } }
if(pos == -1) System.out.println("not found"); else System.out.println("Found at position " + (pos + 1) + " (index " + pos + ")"); } }
Linear search is the counterpart to binary search, and the question names it — so do not offer a binary search however tempting. Linear search checks every element from the start and needs no sorted data.
Three points carry the marks: - pos is initialised to -1, which is what lets you distinguish "not found" from "found at index 0". Using 0 as the not-found marker is the classic bug. - break stops the loop at the FIRST match, which is what a search should do; without it the program would keep scanning and report the last match instead. - the report gives the position. Say clearly whether you mean the index (from 0) or the position (from 1) — printing both, as here, removes any doubt.
A caution worth mentioning in your answer: comparing doubles with == is unreliable in general, because stored values can differ by a tiny rounding amount. For examination purposes == is expected, but a professional program would test whether the difference is smaller than a very small tolerance.
a[] double[20] - the values entered by the user key double - the value to be searched for pos int - index where the key is found, or -1 if absent i int - loop variable sc Scanner - object used to read input