how to sum values in columns in a 2D array?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • ccarter45
    New Member
    • Mar 2008
    • 10

    how to sum values in columns in a 2D array?

    Code:
    public class SumColumn 
    {
      public static void main( String[] args ) 
      {
        int[][] grid = {{1, 2, 3}, {4, 5, 6}}; // array initializer for 2D array
        
        print2DArray("The array is: ", grid);
        
        sumColumn(grid);// write method call to sumColumn here
      }
       
      // print out a 2D array
      public static void print2DArray( String message, int[][] a )
      {
        System.out.println(message);
        
        for ( int i = 0; i < a.length; i++ )
        {
          for ( int j = 0; j < a[0].length; j++ )
          {
            System.out.print(a[i][j] + " ");
          }
          System.out.println();
        }
      }
      
      // sums up 2D array elements column by column
      public static void sumColumn( int[][] a )
      {
    int rows = 2;
    int columns = 3;
        
        
        // nested for loop sums up each row
        int total;
        for( int i = 0; i < a.length; i++ )             // go down rows
        {
          total = 0;
          for( int j = 0; j < a[i].length; j++ )        // print every element in a row
          {          
            total = total + a[i][j];
          }
          System.out.printf( "Column %d sums up to %d.\n", i, total);  
        }
      }
    }
Working...