Two Dimensional Arrays

Introduction to 2D Arrays ( Matrix )
So, far we have seen one dimensional arrays. Now we will see two dimensional array also known as matrix, which is another useful data structure. Consider the declaration below :

int mat [ 3 ][ 4 ];

We have declared a two dimensional array or matrix with 3 rows and 4 columns. We can store 3 x 4 = 12 elements in this matrix. Each element is stored in a cell which can be accessed using the combination of
row index and column index. Initialization of a 2D array is shown below :

Initialization Indexing
int mat[3][4] = { { 17, 23, 15, 19 },
                  { 44, 29, 52, 76 },
                  { 21, 63, 35, 57 } };
17 [ 0, 0 ] 23 [ 0, 1 ] 15 [ 0, 2 ] 19 [ 0, 3 ]
44 [ 1, 0 ] 29 [ 1, 1 ] 52 [ 1, 2 ] 76 [ 1, 3 ]
21 [ 2, 0 ] 63 [ 2, 1 ] 35 [ 2, 2 ] 57 [ 2, 3 ]

We can see how the above initialization statement in the left builds a matrix shown in the right. Every element is stored in a cell which has a index shown as subscript of each element. For e.g, 52 is stored in a cell with index
[ 1, 2 ] where 1 denotes the row number ( index ) and 2 denotes the column number ( index ). Please note that both row and column index starts with 0.
Following program inputs a matrix from user and displays it :

#include<iostream>
using namespace std;

int main() {
   int mat[3][3]; // matrix can have max 3 rows and 3 cols
   int i, j;
   cout << "Enter the matrix elements row-wise :- " << endl;
   for ( i = 0; i < 3; i++ ) { // outer loop iterates over each row
      for ( j = 0; j < 3; j++ ) { // inter loop iterates over each column
         cout << "mat[" << i << "][" << j << "] : ";
         // i -> row no. and j -> col no.
         cin >> mat[i][j];
      }
   }
   // display the matrix
   cout << "You have entered the matrix :- " << endl;
   for ( i = 0; i < 3; i++ ) {
      for ( j = 0; j < 3; j++ ) {
         cout << mat[i][j] << " ";
      }
      cout << endl;
   }
   return 0;
}

Passing 2D Array to Function
2D Arrays (matrices) are passed similar to 1D arrays but the no. of columns must be specified in the argument of the function to which a matrix has been passed. In the following program we implement four functions which takes a matrix as an argument and perform the following functions :
1) Compute sum of left diagonal elements
2) Compute sum of right diagonal elements
3) Print the lower diagonal matrix
4) Print the upper diagonal matrix

/* 
 * This program does the following operations on a matrix 
 * 1) Calculate the sum of left and right diagonal matrix
 * 2) Print the lower and upper diagonal elements
 * For the matrix :  2 3 8 4
                     5 1 7 3
           	     9 2 6 8
           	     1 4 5 7
 * Sum of left diagonal elements = 2 + 1 + 6 + 7 = 16
 * Sum of right diagonal elements = 4 + 7 + 2 + 1 = 14
 * Lower diagonal matrix ( all elements below left diagonal ) : 
   5
   9 2
   1 4 5
 * Upper diagonal matrix ( all elements   above left diagonal ) : 
   3 8 4
     7 3
       8                               
*/

#include<iostream>
using namespace std;

/* computes the sum of left diagonal elements */
int sumLeftDiagElements(int mat[][4], int rows, int cols) {
   int i, j, sum = 0;
   for ( i = 0; i < rows; i++ ) {
      for ( j = 0; j < cols; j++ ) {
         if ( i == j ) { // we found a left diagonal element
            sum += mat[i][j];
         }
      }
   }
   return sum;
}

/* computes the sum of right diagonal elements */
int sumRightDiagElements(int mat[][4], int rows, int cols) {
   int i, j, sum = 0;
   for ( i = 0; i < rows; i++ ) {
      for ( j = 0; j < cols; j++ ) {
         if ( (i + j) == (rows - 1) ) { // we found a right diagonal element
            sum += mat[i][j];
         }
      }
   }
   return sum;
}

/* Print the lower diagonal elements */
void lowerDiagMatrix(int mat[][4], int rows, int cols) {
   int i, j;
   for ( i = 0; i < rows; i++ ) {
      for ( j = 0; j < cols; j++ ) {
         if ( i > j ) { // we found a lower diagonal element
            cout << mat[i][j] << " ";
         }
      }
      cout << endl;
   }
}

/* Print the upper diagonal elements */
void upperDiagMatrix(int mat[][4], int rows, int cols) {
   int i, j;
   for ( i = 0; i < rows; i++ ) {
      for ( j = 0; j < cols; j++ ) {
         if ( i < j ) { // we found a upper diagonal element
            cout << mat[i][j] << " ";
         }
         else {
            cout << "  ";
         }
      }
      cout << endl;
   }
}

int main() {
   int mat[4][4] = { { 2, 3, 8, 4 },
           	     	 { 5, 1, 7, 3 },
           	     	 { 9, 2, 6, 8 },
           	     	 { 1, 4, 5, 7 } };
   int left_diag_sum = sumLeftDiagElements(mat, 4, 4);
   cout << "Sum of Left Diagonal elements : " << left_diag_sum << endl;
   int right_diag_sum = sumRightDiagElements(mat, 4, 4);
   cout << "Sum of Right Diagonal elements : " << right_diag_sum << endl;
   cout << "Lower Diagonal Elements :- ";
   lowerDiagMatrix(mat, 4, 4);
   cout << "Upper Diagonal Elements :- " << endl;
   upperDiagMatrix(mat, 4, 4);
   return 0;
}

Dynamic memory allocation for Two Dimensional Arrays
Similar to 1D arrays, 2D arrays are dynamically allocated and deallocated using new and delete operator.
See the program below :

#include<iostream>
using namespace std;

int main() {
   int **mat, rows = 3, cols = 3, i, j;
   // dynamically allocate memory for a matrix of size m x n
   mat = new int*[rows];
   for ( i = 0; i < rows; i++ ) {
      mat[i] = new int[cols];
   }
   // initialize matrix elements
   for ( i = 0; i < rows; i++ ) {
      for ( j = 0; j < cols; j++ ) {
         mat[i][j] = i + j;         
      }
   }
   // display matrix 
   for ( i = 0; i < rows; i++ ) {
      for ( j = 0; j < cols; j++ ) {
         cout << mat[i][j] << " ";
      }
      cout << endl;
   }
   // deallocate (free) the memory
   for ( i = 0; i < rows; i++ ) {
      delete mat[i];
   }
   delete mat;
   return 0;
}

 

About    Contact    Sitemap    Terms    Privacy