# Accessing Elements of 2-D Array

• December 13, 2022
• C++

Accessing Elements of a 2-D Array:

The most basic type of multidimensional array in C++ is a two-dimensional array. One way to think of it is as an array of arrays. A two-dimensional array is also called a matrix. Let us take a look at the accessing of its elements.

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

• Row Major Order (RMO): This is how a 2D Array’s elements are accessed by default and according to industry standards. Here, we access the elements in rows, starting with the first column and only moving to the second row after accessing all the elements in the first row. This procedure is repeated until we reach the last element in the matrix, which is the one in the final column of the final row. See the code below for a better understanding.
• Column Major Order (CMO): This is an additional method of getting at a 2D Array’s elements. Here, we access the elements in a column-by-column manner, starting from the first row and only accessing the elements in the first column before moving to the second column. Up until the element in the last row of the last column, this process is repeated until we reach the end of the matrix. Please refer to the following code for a better understanding.

Program Code:

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

int main()
{
//loop variable r to iterate rows and c to iterate columns.
int i, j;
int arr[5][2] = {{0, 1},
{2, 3},
{4, 5},
{6, 7},
{8, 9}};

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

cout << "\n\n";

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

cout << "\n\n";

return 0;
}``````

Output:

``````=====  Accessing the array elements in the Row Major Order =====
arr[0][0]: 0
arr[0][1]: 1
arr[1][0]: 2
arr[1][1]: 3
arr[2][0]: 4
arr[2][1]: 5
arr[3][0]: 6
arr[3][1]: 7
arr[4][0]: 8
arr[4][1]: 9

=====  Accessing the array elements in the Column Major Order =====

arr[0][0]: 0
arr[1][0]: 2
arr[2][0]: 4
arr[3][0]: 6
arr[4][0]: 8
arr[0][1]: 1
arr[1][1]: 3
arr[2][1]: 5
arr[3][1]: 7
arr[4][1]: 9``````

Note: also read about Program to Reverse an Array