Varun Rao
Varun Rao

Reputation: 433

Access diagonal elements in a 2D array stored in a 1D array

Suppose my 2D array is:

int a[4][4] = {
               1,0,0,0,
               0,1,0,0,
               0,0,1,0,
               0,0,0,1
              };

Suppose its stored in a 1D array as:

int b[16]={1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1};

In general, assume a is of size m x n and b is of size mn. Using a single for loop I want to be able to access all the diagonal elements, i.e output should be 1 1 1 1.

I understand A[i][j] = B[i*n+j]; but if I'm only using a single for loop, I don't have a j index.

Any help would be highly appreciated.

Edit:

Note let m=n be for all practical purposes. The interface I'm using expects two separate variables for row and column size. But I'm only working with square matrices.

Upvotes: 1

Views: 2669

Answers (3)

VHS
VHS

Reputation: 10174

It's simple to it for a 2-d array.

for(int i=0; i<4; i++)
   printf("%d", a[i][i]);

And for a single dimension array, it is not difficult either.

for(int i=0; i<16; i=i+5)
   printf("%d", b[i]);

Upvotes: 2

Gnqz
Gnqz

Reputation: 3382

You only needto consider the number of columns.

#define COLUMNS 4
#define ROWS 4

b[16]={1,0,0,0,
       0,1,0,0,
       0,0,1,0,
       0,0,0,1};

int i = 0;
for(; i < ROWS; i++ ){
  printf("%d\t",b[COLUMNS*i+i]);
}

Upvotes: 1

Govind Parmar
Govind Parmar

Reputation: 21532

If you know your 2D array is a perfect square (i.e. exactly as many rows as columns), you don't need a j index:

As a 2D array:

for(i = 0; i < height; i++)
{
    printf("%d\n", array[i][i];
}

As a 1D array:

for(i = 0; i < height; i++)
{
    printf("%d\n", array[i*height+i]);
}

Upvotes: 3

Related Questions