Find the Smallest Element in a Matrix

In this post, you will learn how to find the smallest element in a given Matrix in Java. To find the smallest element in a matrix (2D array) in Java, you can iterate through each element of the matrix and keep track of the smallest value encountered so far.

Here’s a Java program to do that:

package com.javacodepoint.array.multidimensional;

public class SmallestElementInMatrix {

	public static int findSmallestElement(int[][] matrix) {

		if (matrix == null || matrix.length == 0) {
			throw new IllegalArgumentException("Input matrix is null or empty.");
		}

		// Initialize with the first element of the matrix
		int smallest = matrix[0][0];

		// Iterate through the matrix and update the smallest value
		// if a smaller element is found
		for (int i = 0; i < matrix.length; i++) {
			for (int j = 0; j < matrix[i].length; j++) {
				if (matrix[i][j] < smallest) {
					smallest = matrix[i][j];
				}
			}
		}

		return smallest;
	}

	public static void main(String[] args) {
		int[][] matrix = { { 4, 12, 6 }, { 8, 3, 0 }, { -5, 9, 7 } };

		int smallestElement = findSmallestElement(matrix);

		System.out.println("Matrix:");
		for (int[] row : matrix) {
			for (int value : row) {
				System.out.print(value + " ");
			}
			System.out.println();
		}

		System.out.println("The smallest element in the matrix: " + smallestElement);
	}
}

OUTPUT:

Matrix:
4 12 6
8 3 0
-5 9 7
The smallest element in the matrix: -5

Explanation:

In this program, we have a findSmallestElement method that takes a 2D matrix as input and returns the smallest element in the matrix.

We initialize the smallest variable with the value of the first element of the matrix (matrix[0][0]). Then, we iterate through the matrix using nested loops. For each element, we compare it with the current value of smallest. If the element is smaller than smallest, we update smallest to the value of the element.

After iterating through the entire matrix, smallest will contain the smallest element.

Learn also: Add the Two Matrices.

Java logical programs list


Java Basic Programs

Java Programs based on the Collection Framework

Leave a Reply

Your email address will not be published. Required fields are marked *