C Programs Tutorials | IT Developer
IT Developer

Java Programs



Share with a Friend

Linear Search Program - Java Programs

Define a class to accept values into an array of double data type of size 20. Accept a double value from user and search in the array using linear search method. If value is found display message “Found” with its position where it is present in the array.

Otherwise display message “not found”.

import java.util.Scanner; class Search{ public static void main(String[] args){ Scanner in = new Scanner(System.in); double a[] = new double[20]; System.out.println("Enter the numbers: "); for(int i = 0; i < a.length; i++) a[i] = Double.parseDouble(in.nextLine()); System.out.print("Enter value to be searched: "); double key = Double.parseDouble(in.nextLine()); int i = 0; while(i < a.length){ if(key == a[i]) break; i++; } if(i == a.length) System.out.println("not found"); else System.out.println("Found at position " + i); } }

Output

 
 OUTPUT : 
Enter the numbers: 
1
4
6
2
5
3
7
9
8
10
12
11
15
14
13
19
20
16
18
17
Enter value to be searched: 6
Found at position 2