Programming Example
Write a Java program to search multiple values in an array.
Study this program carefully to understand the logic, output, and explanation in a structured way.
int[] arr = {5, 10, 15, 20, 25};
int[] searchValues = {10, 25, 30};
10 found at index 1 25 found at index 4 30 not found
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");
}
}
}
}
The program uses nested loops to search multiple values one by one inside the same array.
First read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.
After understanding this example, try to rewrite the same program without looking at the code. Then change some values or logic and run it again. This helps improve confidence and keeps learners engaged on the page for longer.