papap123 - 22 days ago 7
C Question

# Moving elements in 2d array for c

So I have 2d array filled with random numbers .For example:

``````#define d 4

int main(void)
{
int a[d][d];
int primary[d], secondary[d];
size_t i, j;

srand(time(NULL));

/* fill array with random numbers */
for (i = 0; i < d; i++)
for (j = 0; j < d; j++)
a[i][j] = rand() % 100;

/* save diagonals */
for (i = 0; i < d; i++)
{
primary[i] = a[i][i];
secondary[i] = a[d - (i + 1)][i];
``````

How to mirror horizontally diagonals?

For example:

``````1  0  0  2

0  3  4  0

0  5  6  0

7  0  0  8
``````

``````8  0  0  7

0  6  5  0

0  4  3  0

2  0  0  1
``````

Task is to print main matrix and then print matrix with mirrored diagonals however i got no ideas how cycle for this should look like.

I thought about cycle for rotating matrix for 180 degrees however I will loose the positions of elements that are not included to the diagonals.

Or can i save diagonal and then reverse it somehow.
Here is code for matrix and diagonal what should i do now.

One of approaches is the following

``````#include <stdio.h>

#define N   4

int main(void)
{
int a[N][N] =
{
{ 1,  0,  0,  2 },
{ 0,  3,  4,  0 },
{ 0,  5,  6,  0 },
{ 7,  0,  0,  8 }
};

for ( size_t i = 0; i < N; i++ )
{
for ( size_t j = 0; j < N; j++ ) printf( "%d ", a[i][j] );
printf( "\n" );
}

printf( "\n" );

for ( size_t i = 0; i < N * N / 2; i++ )
{
int tmp = a[i / N][i % N];
a[i / N][i % N] = a[(N * N - i - 1) / N][(N * N - i - 1) % N];
a[(N * N - i - 1) / N][(N * N - i - 1) % N] = tmp;
}

for ( size_t i = 0; i < N; i++ )
{
for ( size_t j = 0; j < N; j++ ) printf( "%d ", a[i][j] );
printf( "\n" );
}

printf( "\n" );

return 0;
}
``````

The program output is

``````1 0 0 2
0 3 4 0
0 5 6 0
7 0 0 8

8 0 0 7
0 6 5 0
0 4 3 0
2 0 0 1
``````

The same can be written using pointers. For example

``````#include <stdio.h>

#define N   4

int main(void)
{
int a[N][N] =
{
{ 1,  0,  0,  2 },
{ 0,  3,  4,  0 },
{ 0,  5,  6,  0 },
{ 7,  0,  0,  8 }
};

for ( size_t i = 0; i < N; i++ )
{
for ( size_t j = 0; j < N; j++ ) printf( "%d ", a[i][j] );
printf( "\n" );
}

printf( "\n" );

for ( int *first = ( int * )a, *last = ( int * )a + N * N;
first < last;
++first, --last )
{
int tmp = first[0];
first[0] = last[-1];
last[-1] = tmp;
}

for ( size_t i = 0; i < N; i++ )
{
for ( size_t j = 0; j < N; j++ ) printf( "%d ", a[i][j] );
printf( "\n" );
}

printf( "\n" );

return 0;
}
``````
Source (Stackoverflow)