Moving elements in 2d array for c -
so have 2d array filled 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 random numbers */ (i = 0; < d; i++) (j = 0; j < d; j++) a[i][j] = rand() % 100; /* save diagonals */ (i = 0; < d; i++) { primary[i] = a[i][i]; secondary[i] = a[d - (i + 1)][i];
how 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 print main matrix , print matrix mirrored diagonals got no ideas how cycle should like.
i thought cycle rotating matrix 180 degrees loose positions of elements not included diagonals.
or can save diagonal , reverse somehow. here code matrix , diagonal should now.
hope help.
one of approaches 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 } }; ( size_t = 0; < n; i++ ) { ( size_t j = 0; j < n; j++ ) printf( "%d ", a[i][j] ); printf( "\n" ); } printf( "\n" ); ( size_t = 0; < n * n / 2; i++ ) { int tmp = a[i / n][i % n]; a[i / n][i % n] = a[(n * n - - 1) / n][(n * n - - 1) % n]; a[(n * n - - 1) / n][(n * n - - 1) % n] = tmp; } ( size_t = 0; < n; i++ ) { ( 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 written using pointers. 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 } }; ( size_t = 0; < n; i++ ) { ( size_t j = 0; j < n; j++ ) printf( "%d ", a[i][j] ); printf( "\n" ); } printf( "\n" ); ( int *first = ( int * )a, *last = ( int * )a + n * n; first < last; ++first, --last ) { int tmp = first[0]; first[0] = last[-1]; last[-1] = tmp; } ( size_t = 0; < n; i++ ) { ( size_t j = 0; j < n; j++ ) printf( "%d ", a[i][j] ); printf( "\n" ); } printf( "\n" ); return 0; }
Comments
Post a Comment