C++ Program to Access the elements of a Matrix (2D Array)

Hello Everyone!

In this tutorial, we will learn how to access the elements of a Matrix (2D Array), in the C++ programming language.

In programming, a Matrix is nothing but a 2D Array. These two dimensions are referred to as rows and columns.

There are 2 ways to access the elements of a Matrix:

  1. Row Major Order (RMO): This is the default and the standard way to access the elements of a 2D Array. Here we access the elements row-wise, i.e. we first access all the elements of the 1st row and then only move to the 2nd row, again starting from the 1st column. This process is repeated until we reach the end of the matrix i.e. the element at the last column of the last row. For better understanding, refer to the code below.

  2. Column Major Order (CMO): This is another way to access the elements of a 2D Array. Here we access the elements column-wise, i.e. we first access all the elements of the 1st column and then only move to the 2nd column, again starting from the 1st row. This process is repeated until we reach the end of the matrix i.e. the element at the last row of the last column. For better understanding, refer to the code below.

Code:

#include <iostream>
using namespace std;

int main()
{
    cout << "\n\nWelcome to Studytonight :-)\n\n\n";
    cout << " =====  Program to demonstrate accessing the elements of a Matrix ===== \n\n";

    //loop variable r to iterate rows and c to iterate columns.
    int r, c;

    //declaring and initializing the 2D array.
    int arr[5][2] = {{0, 0},
                   {11, 22},
                   {22, 44},
                   {33, 66},
                   {44, 88}};   

    cout << " =====  Accessing the array elements in the Row Major Order ===== \n\n";    
    // outputing the value of each of the array element
    for (r = 0; r < 5; r++)
    {
        for (c = 0; c < 2; c++)
        {
            cout << "arr[" << r << "][" << c << "]: ";
            cout << arr[r][c] << endl;
        }
    }
             
    cout << "\n\n";

    cout << " =====  Accessing the array elements in the Column Major Order ===== \n\n";    
    // outputing the value of each of the array element
    for (c = 0; c < 2; c++)
    {
        for (r = 0; r < 5; r++)
        {
            cout << "arr[" << r << "][" << c << "]: ";
            cout << arr[r][c] << endl;
        }
    }
             
    cout << "\n\n";

    return 0;
}

Output:

C++ Access array elements

We hope that this post helped you develop better understanding about the differenet ways to access the elements of a 2D array. For any query, feel free to reach out to us via the comments section down below.

Keep Learning : )