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
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

Popular posts from this blog

Program to define a class 'employee' with data members as empid, name and salary. Accept data for 5 objects using Array of objects and print it.

Define a class Student with four data members such as name, roll no.,sub1, and sub2. Define appropriate methods to initialize and display the values of data members. Also calculate total marks and percentage scored by student.

Program to input age from user and throw user-defined exception if entered age is negative