Write a Java program to perform searching (linear search).
import java.util.Scanner;
public class Searching {
public static void main(String[] args) {
int arr[] = new int[10];
int key;
int found=0;
Scanner s = new Scanner(System.in);
System.out.println("Enter 10 elements...");
for(int i=0; i<10; i++) {
arr[i] = s.nextInt();
}
System.out.print("Enter the element to search :: ");
key = s.nextInt();
for(int i=0; i<10; i++) { // for-each loop
if (arr[i] == key) {
found = i;
break;
}
}
if (found != 0) {
System.out.println("Element is found at " + (found+1) + " location");
}
else {
System.out.println("Element is not found");
}
}
}
Enter 10 elements...
12
56
23
45
85
64
51
47
11
95
Enter the element to search :: 47
Element is found at 8 location