×

Welcome to TagMyCode

Please login or create account to add a snippet.
0
0
 
0
Language: Java
Posted by: Vusi Mbonani
Added: Aug 13, 2021 9:14 PM
Views: 3791
Tags: no tags
  1. package multidimensionarray;
  2. /**
  3.  *This code snippet demonstrates on how to calculate
  4.  * the sum of each row and column in a
  5.  * Multidimensional Array.
  6.  * @author VD MBONANI
  7.  */
  8. public class MultiDimensionArray {
  9.     /**
  10.      * @param args the command line arguments
  11.      */
  12.     public static void main(String[] args) {
  13.         //Declaring row and column constants.
  14.         final int ROWS = 3;
  15.         final int COLS =3;
  16.         //Declaring an initialized 2-D dimensional Array of type integer.
  17.         int[][]values = {{1,2,3},
  18.                          {4,5,6},
  19.                          {7,8,9}};
  20.         //Calculating the sum of each row.          
  21.         for(int x = 0; x < ROWS; ++x){
  22.             //Declaring a running total variable.
  23.             int sumRows = 0;
  24.             for(int y = 0; y < COLS; ++y){
  25.                 //Adding the the values of in a column.
  26.                 sumRows = sumRows + values[x][y];
  27.             }
  28.             //Displaying the sum of each row.
  29.            System.out.println("Sum of Row "+(x + 1)+": "+sumRows);
  30.         }
  31.         //Printing an empty space.
  32.         System.out.println("");
  33.         //Calculating the sum of each column.
  34.         for(int y = 0; y < COLS; ++y){
  35.             //Declaring a running total variable.
  36.             int sumCol = 0;
  37.             for(int x = 0; x < ROWS; ++x){
  38.                 //Adding the the values of in a column.
  39.                 sumCol = sumCol + values[x][y];
  40.             }
  41.             //Displaying the sum of each column.
  42.             System.out.println("Sum of Column "+(y + 1)+": "+sumCol);
  43.         }
  44.     }
  45. }
  46.