Search code examples
javafor-loopsumcalculated-columns

Sum of the column in 2D Array, Java


I was trying to sum the each column but I failed to get the expected output, as you can see I take the element of this 2d array like normal(row and col), but for the For-loop I loop the column first then loop the row.

input;

3
4
1 2 3 4
4 5 6 5
7 8 9 5

expected outout;

12
15
18
14

my output;

6
13
18
22

my code;

import java.util.Scanner;
    public class exercise2_2darray {
        public static void main(String[] args) {
            
            Scanner sc=new Scanner(System.in);   
            int m = sc.nextInt();  //take input row 
            int n = sc.nextInt();  //take input col 
            int array[][] = new int[m][n];      
            
            for(int col =0; col<n; col++) { 
                  int Sum = 0; 
                  
                for (int row=0;row<m; row++) {
                        
                    array[row][col] = sc.nextInt();     
                    Sum+=array[row][col];               
                }           
                System.out.println(Sum);            
            }   
        }
    }

the right answer is to seperate the taking user input for loop and the array sum loop;

import java.util.Scanner;
public class exercise2_2darray {
    public static void main(String[] args) {
        
        Scanner sc=new Scanner(System.in);   
        int m = sc.nextInt();  //take input row 
        int n = sc.nextInt();  //take input col 
        int array[][] = new int[m][n];      
        
        for(int row =0; row<m; row++) { 
                  
            for (int col=0;col<n; col++) {
                    
                array[row][col] = sc.nextInt();                         
            }                               
        }
        
        for(int col =0; col<n; col++) { 
              int Sum = 0; 
              
            for (int row=0;row<m; row++) {
                        
                Sum+=array[row][col];               
            }           
            System.out.println(Sum);            
        }   
        
    }
}

Solution

  • The way you are entering input is wrong. You have switch row and column which results your input be like this.

    1  4  6  8
    2  4  5  9
    3  5  7  5
    

    and sum be

    6  13  18  22
    

    Either you'll have to change how you enter input

    1  4  7
    2  5  8
    3  6  9
    4  5  5
    

    or switch row and col back to usual(row as outer loop and column as inner loop) for taking input and doing sum separately in another loop

    for(int row=0; row<r; row++) {
        for(int col=0; col<n; col++) {
            ....// take input
        }
    }
    for(int row=0; row<r; row++) {
        int sum=0;
        for(int col=0; col<n; col++) {
            Sum+=array[row][col];
        }
        System.out.println(Sum);
    }