如何使用嵌套循环翻转数组元素,如下所示?
-1 -2 -3 3 2 1
4 5 6 --------> 4 5 6
1 2 3 -3 -2 -1
非常感谢^ _ ^
答案 0 :(得分:1)
如果我理解正确你需要这样的东西
#include <stdio.h>
#define N 3
int main(void)
{
int a[N][N] =
{
{ -1, -2, -3 },
{ 4, 5, 6 },
{ 1, 2, 3 }
};
for ( size_t i = 0; i < N; i++ )
{
for ( size_t j = 0; j < N; j++ ) printf( "%2d ", a[i][j] );
putchar( '\n' );
}
putchar( '\n' );
for ( size_t i = 0; i < N / 2; i++ )
{
for ( size_t j = 0; j < N; j++ )
{
int tmp = a[i][j];
a[i][j] = a[N - 1 - i][N - 1 - j];
a[N - 1 - i][N - 1 - j] = tmp;
}
}
for ( size_t i = 0; i < N; i++ )
{
for ( size_t j = 0; j < N; j++ ) printf( "%2d ", a[i][j] );
putchar( '\n' );
}
putchar( '\n' );
return 0;
}
程序输出
-1 -2 -3
4 5 6
1 2 3
3 2 1
4 5 6
-3 -2 -1