title: How to calculate the sum of each column in a 2D array?
body: <p>I'm writing a program so that it computes and prints the sum of each column of the array. The given data looks like this: </p>
  
  <pre><code>int[][] data = {{3, 2, 5},
                  {1, 4, 4, 8, 13},
                  {9, 1, 0, 2},
                  {0, 2, 6, 3, -1, -8}};
  </code></pre>
  
  <p>Ideally, it should output the results 13, 9, 15, 13, 12, -8. But since some of the rows have different lengths, when I run my program, it outputs 13, 9, 15 and gives me an ArrayIndexOutOfBoundsException. And I really don't know how to fix it.</p>
  
  <p>Here is my code:</p>
  
  <pre><code>public class ColumnSums
  {
  public static void main(String[] args) {
  
      //The given data
      int[][] data = {{3, 2, 5},
                      {1, 4, 4, 8, 13},
                      {9, 1, 0, 2},
                      {0, 2, 6, 3, -1, -8}};
  
      //Determine the number of data in the longest row
      int LongestRow = 0;
      for ( int row=0; row &lt; data.length; row++){
          if ( data[row].length &gt; LongestRow ){
              LongestRow = data[row].length;
          }
      }
      System.out.println("The longest row in the array contains " + LongestRow + " values"); //Testing
  
      //Save each row's length into a new array (columnTotal)
      int[] columnTotal = new int[4];
  
      //Scan through the original data again
      //Record each row's length into a new array (columnTotal)
      System.out.println("The lengths of each row are: ");
      for ( int i = 0; i &lt; data.length; i++){
          columnTotal[i] = data[i].length;
          System.out.println(columnTotal[i]); //Testing
      }
  
  
      // Create an array to store all the sums of column
      int ColumnSums[] = new int[LongestRow];
      System.out.println("The sums of each column are: ");
  
      for ( int i = 0; i &lt; LongestRow; i++ ){
  
              int sum = 0;
  
              for (int j = 0; j &lt; data.length; j++) {
                      sum = sum + data[j][i];
              }
  
              ColumnSums[i] = sum;
              System.out.println("Column " + i + ": " + ColumnSums[i]); //Testing
      }
  
  
  }
  }
  </code></pre>
  
  <p>Thanks for your time!!!</p>