Java Program to search an element in array


In this program, You will learn how to search an element in array in Java.


List is: 1 2 3 4 5


Example: How to search an element in array in Java

Run it Now
import java.util.Scanner;

class Main {
    public static void main(String args[]) {

        int i, f = 0, n;
        int arr[] = new int[5];
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter 5 Numbers :");

        for (i = 0; i < 5; i++) {
            arr[i] = sc.nextInt();
        }

        System.out.print("\nEnter a Number for Search :");
        n = sc.nextInt();

        for (i = 0; i < 5; i++) {
            if (n == arr[i]) {
                f = 1;
                break;
            }
        }

        if (f == 1) {
            System.out.println("\nThe Element is Found:" + n);
        } else {
            System.out.println("\nThe Element is Not Found:" + n);
        }

    }
}

Output:

Enter 5 Numbers :10 20 30 40 50
Enter a Number for Search :40
The Element is Found:40