Searching for number
Searching is process of finding of the specific number to check whether it is present in the given list or not. Here the linear search is used in which the number is checked with all the numbers in the list one by one. If the number is matched then it is called as successful search otherwise it is called as unsuccessful search.
PROGRAM
PROGRAM
import java.util.Scanner;
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");
}
}
}
OUTPUT
C:\>javac Searching.java C:\>java Searching 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