使用嵌套循环在C中翻转数组元素数据

时间:2017-04-17 11:33:56

标签: c arrays nested-loops

如何使用嵌套循环翻转数组元素,如下所示?

-1 -2 -3                3  2  1
 4  5  6   -------->    4  5  6 
 1  2  3               -3 -2 -1 

非常感谢^ _ ^

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