Search code examples
javamultidimensional-arrayminimum

I try to find the row with the minimum sum in a 2D array but I only get 0


Why do I get 0's for minRow and minRowIndex? Thank you whoever response.

import java.util.Scanner;

public class test1 {

public static void main(String[] arg) {

    Scanner in = new Scanner(System.in);

    int [][] matrix = {{1, 2, 3, 4, 5}, {2, 3, 4, 5, 6}, {3, 4, 5, 6, 7}};

    int minRow = 0;
    int minRowAvg = 0;
    int minRowIndex = 0;

    for (int row = 1; row < matrix.length; row++){
        int rowSum = 0;
        for (int col = 0; col < matrix[row].length; col++){
            rowSum += matrix[row][col];
        }

        if (rowSum < minRow && rowSum > 0){ 
            minRow = rowSum;
            minRowIndex = row;
        }
    }
    System.out.println("Row " + minRowIndex + " has the minimum sum of " + minRow);

    }

}

Solution

  • rowSum will never be smaller the minRow, since you initialized minRow to 0.

    You should initialize it to Integer.MAX_VALUE.

    int minRow = Integer.MAX_VALUE;