Emulating a 2-d array using 1-d array in C++

C++Server Side ProgrammingProgramming

In this problem, we will understand the conversion of 2-D array to 1-D array. We will see how to store the elements of a 2-D array to a 1-D array.

Here, the size of 1-D array is same as the total number of elements in 2-D array which is n*m.

In programming there are two ways to store a 2-D array to 1-D array. They are−

  • Row Major
  • Column Major

Row Major: In row major, All the elements of a row are stored together then it moves to the next row.

If an element of 2-D array of size nXm has an index (i, j) is stored in 1-D array, its index in 1-D array is

(j) + (i)*m 

Column Major: In column major, all  elements of a column are stored together then the next column is traversed. 

If an element of 2-D array of size nXm has an index (i, j) is stored in 1-D array, its index in 1-D array is

(i) + (j)*n

Lets see an example to understand the problem,

Input: n = 3, m = 5, (i,j) = (0, 2)

Output:      row-major =
                   column-major =

Explanation: 

Row-major = 2 + 0*3 = 3
Col-major = 0 + 2*5 = 10

Program to illustrate the conversion of 2-D to 1-D,

Example

Live Demo

#include<iostream>
using namespace std;

int main() {

int n = 3;
int m = 5;
   int grid[n][m] = {{1, 2, 3},
                {4, 5, 6},
                {7, 8, 9},
    {10, 11, 12},
    {13, 14, 15}};
   int i = 0;
   int j = 2;
   int rowMajorIndex = i*n + j;
   cout<<"Index of element at index (0, 2) in 1-D array using row-major is "<<rowMajorIndex<<endl;
   int colMajorIndex = i + j*m;
   cout<<"Index of element at index (0, 2) in 1-D array using column-major is "<<colMajorIndex<<endl;
   return 0;
}

Output −

Index of element at index (0, 2) in 1-D array using row-major is 2
Index of element at index (0, 2) in 1-D array using column-major is 10
raja
Published on 22-Jan-2021 12:45:20
Advertisements