Java: Find the all positions of a given number in a given matrix

Java Basic: Exercise-194 with Solution

Write a Java program to determine the all positions of a given number in a given matrix. If the number is not found print ("Number not found!").

Visual Presentation:

Java Basic Exercises: Test whether there are two integers x and y

Sample Solution:

Java Code:

// Main class for the solution
public class Solution {

    // Main method to execute the solution
    public static void main(String[] args) {
        // Initialize the target number
        int num = 3;

        // Initialize a 2D matrix
        int matrix[][] = {
            {2, 5, 3},
            {3, 2, 1},
            {1, 3, 5}

        // Get the number of rows in the matrix
        int r = matrix.length;

        // Get the number of columns in the matrix
        int c = matrix[0].length - 1;

        // Initialize variables for matrix traversal
        int m = 0, n = 0;

        // Boolean flag to check if the number is found in the matrix
        Boolean flag = false;

        // Iterate through the rows of the matrix
        while (m < r) {
            // Iterate through the columns of the matrix
            while (n <= c) {
                // Check if the current element is equal to the target number
                if (matrix[m][n] == num) {
                    // Display the coordinates of the found number
                    System.out.print("\n(" + m + "," + n + ")\n");
                    // Set the flag to true indicating the number is found
                    flag = true;
                // Move to the next column

            // Move to the next row and reset column index
            n = 0;

        // Display a message if the number is not found in the matrix
        if (flag == false)
            System.out.print("Number not found!");

Sample Output:





Flowchart: Java exercises: Find the all positions of a given number in a given matrix

Java Code Editor:

Company:  LinkedIn

Contribute your code and comments through Disqus.

Previous: Write a Java program that accept an integer and find the sum of all the elements from all possible subsets of a set formed by first n natural numbers.
Next: Write a Java program to check if three given side lengths (integers) can make a triangle or not.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

Follow us on Facebook and Twitter for latest update.