Min Value of a 2D Array diagonally? [Java]

I’m currently stuck on finding a min value of 2D array diagonal? For example if i had

2 1 3
4 5 6
9 8 7

I’d want the diagonal min of 2, 5 ,7. As of now I have a nested for loop that prints 0, honestly my code below is pretty useless but might as well post it.

double minD = 0;
    for (int row = 0; row < a.length; row++) {
      for (int col = 0; col < a[row].length; col++) {
        minD = Math.min(minD, a[row][col]);
        System.out.printf("%5.2f", minD);

If anyone can help me out it’d be much appreciated!

Answer

  1. minD initialized with 0 is the problem. Since 0 is lesser than any of your values, the correct output does not come through.

  2. Your code checks for all matrix values, not just the diagonals.

    int arr[][] = {{2, 1, 3}, {4,5,6}, {9,8,7} };
    int min = arr[0][0];
    for(int i=0; i<arr.length; i++) {
        if(arr[i][i]<min)
           min = arr[i][i];
    }
    System.out.println(min);
    

This code checks just for diagonal elements.

Leave a Reply

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