Write a Java program to search for a specific element in a 2D array and print its position (row and column index). If the element is not found, print a message indicating that the element was not found.
Given the following 2D array:
int[][] arr = { {5, 7, 9}, {4, 6, 8}, {1, 2, 3} };
Single Choice
Views 61
Answer:
public class Main { public static void main(String[] args) { int[][] arr = { {5, 7, 9}, {4, 6, 8}, {1, 2, 3} }; int searchElement = 6; boolean found = false; for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr[i].length; j++) { if (arr[i][j] == searchElement) { System.out.println("Element " + searchElement + " found at position: [" + i + "][" + j + "]"); found = true; break; } } if (found) break; } if (!found) { System.out.println("Element " + searchElement + " not found."); } } }
Related Articles:
This section is dedicated exclusively to Questions & Answers. For an in-depth exploration of Java Programming Language, click the links and dive deeper into this subject.
Join Our telegram group to ask Questions
Click below button to join our groups.