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:
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
Please follow me to read my latest post on programming and technology if you like my post.
https://www.instagram.com/coderz.py/
https://www.facebook.com/coderz.py
Staying up to the mark is what defines me. Hi all! I’m Rabecca Fatima a keen learner, great enthusiast, ready to take new challenges as stepping stones towards flying colors.
The formula for the area of a circle is given by πr². Use the Monte…
Given an integer k and a string s, write a function to determine the length…
There is a staircase with N steps, and you can ascend either 1 step or…
Build an autocomplete system that, given a query string s and a set of possible…
Design a job scheduler that accepts a function f and an integer n. The scheduler…
Problem Statement (Asked By Airbnb) Given a list of integers, write a function to compute…