Search code examples
javaarraysfor-looprowchecksum

How to get the sum for each row?


I want to find and display the row number that has the maximum sum and display the row values and this is sample input/output: enter image description here

The problem is every time the maximum sum is the third row how to solve these issues.

   int [][] scores = new int[4][3];

    for (int i=0; i<scores.length; i++)
    {
        System.out.print("Enter values for row "+i+": ");
        for (int j=0; j<scores[i].length;j++)
            scores[i][j] = kbd.nextInt();
    }
    
    int sum, sumMax, ii=0;
    for (int i=0; i<scores.length; i++)
    {
        sum =0; sumMax = 0; ii=0;
        for (int j=0; j<scores[i].length;j++)
        {
            sum += scores[i][j];
            if (sum>sumMax)
            {
                sumMax = sum;
                ii = i;
            }
        }
    }

    System.out.println("Row "+ii+" has the maximum sum");
    System.out.print("Row "+ii+" has the following values: ");
    for (int j = 0; j < 3; j++)
           System.out.print(scores[ii][j] + " ");

Solution

  • To print a specific row, you need one loop only

    System.out.print("Row " + ii + " has the following values: ");
    for (int j = 0; j < 3; j++)
        System.out.print(scores[ii][j] + " ");
    

    Or with Arrays.toString

    System.out.println("Row " + ii + " has the following values: " + Arrays.toString(scores[ii]));
    

    Also your finding max code is wrong, as you reset ii and sumMax to 0 for each row, the max can only be the last line, you need to keep track of these 2 along the rows. Also use the if only after computing the row's sum, no need to test at every bow of every row

    int sum, sumMax = Integer.MIN_VALUE, ii = 0;
    for (int i = 0; i < scores.length; i++) {
        sum = 0;
    
        for (int j = 0; j < scores[i].length; j++) {
            sum += scores[i][j];
        }
    
        if (sum > sumMax) {
            sumMax = sum;
            ii = i;
        }
    }