Define and initiate a two-dimensional array : Array Two Dimension « Data Structure « C++






Define and initiate a two-dimensional array

Define and initiate a two-dimensional array


#include <iostream>
#include <iomanip>
using namespace std;

int matrix[3][5] = { { 215, 314, 216, 112,  8 },
                     { 119, 217, 214, 111,  4 },
                     {  61, 115, 315, 316, 118 } };
int rowsum[3];    
int colsum[5];    
                  
int matrixsum( int arr2D[][5], int vlen, int rsum[], int csum[]);
int main()
{
   cout << "Testing the function matrixsum()." << endl;

   int totalsum = matrixsum( matrix, 3, rowsum, colsum);

   cout << "The matrix with the sums of rows and columns:" << endl;
   int i,j;
   for( i = 0 ; i < 3 ; ++i)    
   {                            // matrix with row sums.
     for( j = 0 ; j < 5 ; ++j)
       cout << setw(8) << matrix[i][j];
     cout << " | " << setw(8) << rowsum[i] << endl;
   }
   cout << endl;
   for( j = 0 ;  j < 5  ;  ++j )
     cout << setw(8) << colsum[j];
   cout << " | " << setw(8) << totalsum << endl;
   return 0;
}

int matrixsum( int v[][5], int len, int rsum[], int csum[])
{  
   int ro, co;                      // Row and column index
   
   for( ro = 0 ; ro < len ; ++ro)    // To compute row sums
   {
      rsum[ro] = 0;
      for( co = 0 ; co < 5 ; ++co)
        rsum[ro] += v[ro][co];
   }
   for(co = 0 ; co < 5 ; ++co)       // Compute column sums
   {
      csum[co] = 0;
      for( ro = 0 ; ro < len ; ++ro)
        csum[co] += v[ro][co];
   }
   return (rsum[0] + rsum[1] + rsum[2]);  // Total sum =
}                                       // sum of row sums.

           
       








Related examples in the same category

1.Create a two-dimensional array of objects.Create a two-dimensional array of objects.
2.Init two dimension class arrayInit two dimension class array
3.Multidimensional ArraysMultidimensional Arrays