题目:给出一个5*5的二维数组一组数,要求螺旋打印(如下图所示)
方法:设置四个标志位控制四个打印方向(如图),分四个for循环打印
当Left<=Right&&Up<=Down,说明还有数据。
代码如下:
#include<stdio.h>
int main() {
const int n = 5;
const int m = 5;
int ar[n][m] = {
{1, 3, 5, 7, 9 },
{10,12,14,16,18},
{20,22,24,26,28},
{30,32,34,36,38},
{40,42,44,46,48},
};
int Left = 0, Right = n - 1, Up = 0, Down = m - 1;
while (Left <= Right && Up <= Down) {
for (int i = Left; i <= Right; i++) { //i<=Right指包括等于时需要打印的
printf("%5d", ar[Up][i]);//i变量控制列,列在发生变化
}
printf("\n");
for (int i = Up+1; i <= Down; i++) { //i<=Down 包括=
printf("%5d", ar[i][Right]);//i变量控制行,行在发生变化
}
printf("\n");
for (int i = Right - 1; i >= Left && Up <= Down; i--) { //i>=Left 包括=
printf("%5d", ar[Down][i]);
}
printf("\n");
for (int i = Down - 1; i > Up && Left <= Right; i--) { //i>Up 不包括= 才可以形成螺旋打印,不重复打印!!
printf("%5d", ar[i][Left]);
}
printf("\n");
Left++, Right--, Up++, Down--;//千万别忘记控制循环变量的改变!
}
printf("\n");
return 0;
}
?结果如下:(为了方便检查,在每一组打印结束后输出一个换行符)
?其他二维数组螺旋打印也类似。足够细心一定可以掌握的!加油!
|