Java Program to search an element in the array


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


List is: 1 2 3 4 5

Example: How to search an element in an array in java.

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("Enter 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("Element is found:" + n);
        } else {
            System.out.println("Element is not found:" + n);
        }

    }
}

Output:

Enter 5 numbers:10 20 30 40 50
Enter a number for search:30
Element is found:30

Xiith is created for educational, experimental, and schooling purpose. Examples on Xiith are made easier to make a better or basic understanding. Tutorials, testimonials, and examples are continuously checked to avoid delusion, but we cannot take complete responsibility of all programs on Xiith. When you are operating this site, you have to agree to read and accept our terms of use, cookie and privacy policy.Copyright © 2020 by Xiith. All Rights Reserved. About us.