Loading
Data-structure-with-JAva-Tutorial

Searching

 Searching is a method to find the location or position of the element in the array.


Program Solution :

package QuipoHouse.ArrayOperations;

import java.util.Scanner;

public class Searching {

	public static void main(String[] args) {
		int arr[] = new int[20];
		int i;

		// Scanner class for taking values
		Scanner sc = new Scanner(System.in);
		System.out.println("Enter the num of element of Array less than 20:");
		int n = sc.nextInt();

		// Entering n element in Array
		System.out.println("Enter the element in Array:");
		for (i = 0; i < n; i++) {
			arr[i] = sc.nextInt();
		}
		System.out.println("Enter the element to be Searched:");
		int element = sc.nextInt();

		// Searching
		for (i = 0; i < n; i++) {
			if (arr[i] == element) {
				System.out.println("Element found at: " + (i + 1));
			}
		}
	}
}

Output:

Enter the num of element of Array less than 20:
5
Enter the element in Array:
9
4
6
2
8
Enter the element to be Searched:
2
Element found at: 4