Write a Java program to search multiple values in an array.

Java Fundamentals: Building Strong Foundations (Article) (Program)

7

Given Input:


 int[] arr = {5, 10, 15, 20, 25};
        int[] searchValues = {10, 25, 30};

Expected Output:

10 found at index 1
25 found at index 4
30 not found

Program:

class SearchMultipleElements {
    public static void main(String[] args) {
        int[] arr = {5, 10, 15, 20, 25};
        int[] searchValues = {10, 25, 30};

        for (int i = 0; i < searchValues.length; i++) {
            boolean found = false;

            for (int j = 0; j < arr.length; j++) {
                if (arr[j] == searchValues[i]) {
                    System.out.println(searchValues[i] + " found at index " + j);
                    found = true;
                    break;
                }
            }

            if (!found) {
                System.out.println(searchValues[i] + " not found");
            }
        }
    }
}

Output:


                                        

Explanation:

The program uses nested loops to search multiple values one by one inside the same array.