Loading
Searching-tutorial
Searching in an array means finding the location or index of a specific element in the array. It is a fundamental operation in data structures.
we use the Linear Search technique, which checks each element one by one.



Key Point

  • The array is traversed from start to end.
  • If the searched element matches any array value, its position is printed.
  • Indexing starts at 0, but the position is displayed starting from 1 for user-friendliness.



Example: Search an Element in an Array

package QuipoHouse.ArrayOperations;

import java.util.Scanner;

public class Searching {

    public static void main(String[] args) {
        int arr[] = new int[20];  // Declaring array with max size 20
        int i;

        // Input setup
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the number of elements in the array (less than 20):");
        int n = sc.nextInt();

        // Reading array elements
        System.out.println("Enter " + n + " elements:");
        for (i = 0; i < n; i++) {
            arr[i] = sc.nextInt();
        }

        // Reading the element to be searched
        System.out.println("Enter the element to be searched:");
        int element = sc.nextInt();

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

        // If not found
        if (!found) {
            System.out.println("Element not found in the array.");
        }
    }
}

Output:

Enter the number of elements in the array (less than 20):
5
Enter 5 elements:
9
4
6
2
8
Enter the element to be searched:
2
Element found at position: 4

Explanation

LineDescription
arr[ ] = new int[20]Declares an integer array of size 20
for (i = 0; i < n; i++)Reads n elements into the array
if (arr[i] == element)Checks if current element matches the one we are searching
System.out.println(. . .)Prints the position (1-based index) of the found element
found = trueFlag to ensure we track if the element was found



Use Case

Searching is used in:

  • Form validation (e.g., checking duplicates)
  • Data filtering
  • User input verification
  • Building more advanced algorithms like binary search or search trees