Two Dimensional Array in C++

Introduction

A two-dimensional array in C++ is the simplest form of a multi-dimensional array. It can be visualized as an array of arrays. The image below depicts a two-dimensional array.

A two-dimensional array is also called a matrix. It can be of any type like integer, character, float, etc. depending on the initialization. In the next section, we are going to discuss how we can initialize 2D arrays.

Initializing a 2D array in C++

So, how do we initialize a two-dimensional array in C++? As simple as this:

 int arr[4][2] = {
        {1234, 56},
        {1212, 33},
        {1434, 80},
        {1312, 78}
    };

So, as you can see, we initialize a 2D array arr, with 4 rows and 2 columns as an array of arrays. Each element of the array is yet again an array of integers.

We can also initialize a 2D array in the following way.

    int arr[4][2] = {1234, 56, 1212, 33, 1434, 80, 1312, 78};

Printing a 2D Array in C++

We are done initializing a 2D array, now without actually printing the same, we cannot confirm that it was done correctly.

Also, in many cases, we may need to print a resultant 2D array after performing some operations on it. So how do we do that?

The code below shows us how we can do that.

#include<iostream>
    using namespace std;
    main( ) 
    {  
        int arr[4][2] = {
            { 10, 11 },
            { 20, 21 },
            { 30, 31 },
            { 40, 41 }
        };
        
        int i,j;
        
        cout<<"Printing a 2D Array:\n";
        for(i=0;i<4;i++)
        {
            for(j=0;j<2;j++)
            {
                cout<<"\t"<<arr[i][j];
            }
            cout<<endl;
        }
    }

In the above code,

  • We firstly initialize a 2D array, arr[4][2] with certain values,
  • After that, we try to print the respective array using two for loops,
  • the outer for loop iterates over the rows, while the inner one iterates over the columns of the 2D array,
  • So, for each iteration of the outer loop, i increases and takes us to the next 1D array. Also, the inner loop traverses over the whole 1D array at a time,
  • And accordingly, we print the individual element arr[ i ][ j ].

Taking 2D Array Elements As User Input

Previously, we saw how we can initialize a 2D array with pre-defined values. But we can also make it user input too. Let us see how:

#include<iostream>
    using namespace std;
    main( ) 
    {  
        int  s[2][2];
        int  i, j;
        cout<<"\n2D Array Input:\n";
        for(i=0;i<2;i++)
        {
            for(j=0;j<2;j++)
            {
                cout<<"\ns["<<i<<"]["<<j<<"]= "; cin>>s[i][j];
            }
        } 
        
        cout<<"\nThe 2-D Array is:\n";
        for(i=0;i<2;i++)
        {
            for(j=0;j<2;j++)
            {
                cout<<"\t"<<s[i][j];
            }
            cout<<endl;
        } 
    }

For the above code, we declare a 2X2 2D array s. Using two nested for loops we traverse through each element of the array and take the corresponding user inputs. In this way, the whole array gets filled up, and we print out the same to see the results.

Matrix Addition using Two Dimensional Arrays in C++

As an example, let us see how we can use 2D arrays to perform matrix addition and print the result:

#include<iostream>
    using namespace std;
    main() 
    {  
        int  m1[5][5], m2[5][5], m3[5][5];
        int  i, j, r, c;
        
        cout<<"Enter the no. of rows of the matrices to be added (max 5):"; cin>>r;
        cout<<"Enter the no. of columns of the matrices to be added (max 5):"; cin>>c;
        
        cout<<"\n1st Matrix Input:\n";
        for(i=0;i<r;i++)
        {
            for(j=0;j<c;j++)
            {
                cout<<"\nmatrix1["<<i<<"]["<<j<<"]= "; cin>>m1[i][j];
            }
        } 
        
        cout<<"\n2nd Matrix Input:\n";
        for(i=0;i<r;i++)
        {
            for(j=0;j<c;j++)
            {
                cout<<"\nmatrix2["<<i<<"]["<<j<<"]= "; cin>>m2[i][j];
            }
        } 
        
        cout<<"\nAdding Matrices...\n";
        
        for(i=0;i<r;i++)
        {
            for(j=0;j<c;j++)
            {
                m3[i][j] = m1[i][j] + m2[i][j];
            }
        } 
        
        cout<<"\nThe resultant Matrix is:\n";
    
        for(i=0;i<r;i++)
        {
            for(j=0;j<c;j++)
            {
                cout<<"\t"<<m3[i][j];
            }
            cout<<endl;
        } 
        
    }

Here,

  • We take two matrices m1 and m2 with a maximum of 5 rows and 5 columns. And another matrix m3 in which we are going to store the result,
  • As user inputs, we took the number of rows and columns for both the matrices. Since we are performing matrix addition, the number of rows and columns should be the same for both the matrices,
  • After that, we take both the matrices as user inputs, again using nested for loops,
  • At this point, we have both the matrices m1 and m2,
  • then we traverse through the m3 matrix, using two for loops and update the respective elements m3[ i ][ j ] by the value of m1[i][j]+m2[i][j]. In this way, by the end of the outer for loop, we get our desired matrix,
  • At last, we print out the resultant matrix m3.

Pointer to a 2D Array in C++

If we can have a pointer to an integer, a pointer to a float, a pointer to a char, then can we not have a pointer to an array? We certainly can. The following program shows how to build and use it:

#include<iostream>
    using namespace std;
    /* Usage of pointer to an array */ 
    main( ) 
    {  
        int  s[5][2] = {
            {1, 2},
            {1, 2},
            {1, 2},
            {1, 2}
            } ;
            
        int (*p)[2] ;
        int  i, j;
        for (i = 0 ; i <= 3 ; i++)
        {
            p = &s[i];
            cout<<"Row"<<i<<":";
            for (j = 0; j <= 1; j++)
                cout<<"\t"<<*(*(p+j));
            cout<<endl;
        } 
        
    }

Here,

  • In the above code, we try to print a 2D array using pointers,
  • As we earlier did, at first we initialize the 2D array, s[5][2]. And also a pointer (*p)[2], where p is a pointer which stores the address of an array with 2 elements,
  • As we already said, we can break down a 2D array as an array of arrays. So in this case, s is actually an array with 5 elements, which further are actually arrays with 2 elements for each row.
  • We use a for loop to traverse over these 5 elements of the array, s. For each iteration, we assign p with the address of s[i],
  • Further, the inner for loop prints out the individual elements of the array s[i] using the pointer p. Here, (*p + j) gives us the address of the individual element s[i][j], so using *(*p+j) we can access the corresponding value.

Passing 2-D Array to a Function

In this section, we are going to learn how to pass a 2D array to any function and access the corresponding elements. In the code below, we pass the array a to two functions show() and print() which prints out the passed 2D array:

#include<iostream>
    using namespace std;   
     
    void show(int (*q)[4], int row, int col)
    {
        int  i, j ;
        for(i=0;i<row;i++)
        {
            for(j=0;j<col;j++)
                cout<<"\t"<<*(*(q + i)+j); 
            cout<<"\n";
        }  
        cout<<"\n";
    } 
    
    void print(int  q[][4], int row, int col)
    {
        int  i, j; 
        for(i=0;i<row;i++)
        {   
         for(j=0;j<col;j++)
                cout<<"\t"<<q[i][j];
             cout<<"\n";
        }
       cout<<"\n";
    }
     
    int main() 
    {
        int  a[3][4] = { 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21} ; 
     
        show (a, 3, 4);
        print (a, 3, 4);
        return 0;
    } 

Here,

  • In the show( ) function we have defined q to be a pointer to an array of 4 integers through the declaration int (*q)[4],
  • q holds the base address of the zeroth 1-D array
  • This address is then assigned to q, an int pointer, and then using this pointer all elements of the zeroth 1D array are accessed.
  • Next time through the loop when i takes a value 1, the expression q+i fetches the address of the first 1-D array. This is because q is a pointer to the zeroth 1-D array and adding 1 to it would give us the address of the next 1-D array. This address is once again assigned to q and using it all elements of the next 1-D array are accessed
  • In the second function print(), the declaration of q looks like this: int q[][4],
  • This is same as int (*q )[4], where q is a pointer to an array of 4 integers. The only advantage is that we can now use the more familiar expression q[i][j] to access array elements. We could have used the same expression in show() as well but for better understanding of the use of pointers, we use pointers to access each element.

Conclusion

So, in this article, we discussed two-dimensional arrays in C++, how we can perform various operations as well as its application in matrix addition.

Create a Free Account

Register now and get access to our Cloud Services.

Posts you might be interested in:

centron Managed Cloud Hosting in Deutschland

Android ProgressBar Tutorial in Kotlin

Guide, Linux Basics
Android ProgressBar Tutorial in Kotlin In this tutorial, we’ll discuss and implement ProgressBar in our Android Application using Kotlin. Content1 What is a ProgressBar?2 Android ProgressBar Types3 ProgressBar Attributes4 Android…