1

I have this code, which calculates the sum of all rows in 2D array but I want to print the smallest sum of rows also.

Here down is my code:

package com.example;

import java.util.Arrays;

public class discrete2 {

    public static void main(String[] args) {

        int a[][] = {
                {0, 1, 1, 0, 1, 0, 0, 1, 0},
                {1, 0, 1, 1, 0, 0, 0, 1, 0},
                {1, 0, 0, 1, 0, 1, 1, 0, 1},
                {0, 1, 0, 0, 0, 1, 0, 0, 1},
                {0, 0, 1, 1, 0, 0, 0, 0, 1},
                {1, 0, 0, 0, 0, 0, 1, 1, 0},
                {0, 0, 0, 0, 1, 1, 1, 0, 0}
        };

        int rows = a.length;
        int cols = a[0].length;

        int sumCol;

        for(int i = 0; i < cols; i++){
            sumCol = 0;
            for(int j = 0; j < rows; j++){
                sumCol = sumCol + a[j][i];
            }
            System.out.println("Sum of " + (i+1) +" column: " + sumCol);
        }
    }
}

I tried to changing my code to have variable that remembers the smallest number but it's not working somehow and gives out 3, when it should be 2.

2
  • Your code is working fine, please take a loot at it again Commented Apr 2, 2022 at 10:52
  • Thanks everyone for help, i'm only learning and yall helped me a lot! Commented Apr 2, 2022 at 15:05

1 Answer 1

1
public static void main(String[] args) {
    int a[][] = {
            {0, 1, 1, 0, 1, 0, 0, 1, 0},
            {1, 0, 1, 1, 0, 0, 0, 1, 0},
            {1, 0, 0, 1, 0, 1, 1, 0, 1},
            {0, 1, 0, 0, 0, 1, 0, 0, 1},
            {0, 0, 1, 1, 0, 0, 0, 0, 1},
            {1, 0, 0, 0, 0, 0, 1, 1, 0},
            {0, 0, 0, 0, 1, 1, 1, 0, 0}
    };

    int rows = a.length;
    int cols = a[0].length;

    int sumCol;
    int minSumCol = 100000000; // arbitrary large value

    for (int i = 0; i < cols; i++) {
        sumCol = 0;
        for (int j = 0; j < rows; j++) {
            sumCol = sumCol + a[j][i];
        }
        minSumCol = Math.min(minSumCol, sumCol);
        System.out.println("Sum of " + (i + 1) + " column: " + sumCol);
    }
    System.out.println("Min sum in the matrix is: " + minSumCol);
}

Hi, your code is indeed correct. It does return 2 as the smallest value. This is the output that I got:

Sum of 1 column: 3

Sum of 2 column: 2

Sum of 3 column: 3

Sum of 4 column: 3

Sum of 5 column: 2

Sum of 6 column: 3

Sum of 7 column: 3

Sum of 8 column: 3

Sum of 9 column: 3

Min sum in the matrix is: 2

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.