请你设计一个用于填充n阶方阵的上三角区域的程序。填充的规则是:使用1,2,3….的自然数列,从左上角开始,按照顺时针方向螺旋填充。
例如:当n=3时,输出:
1 2 3
6 4
5
当n=4时,输出:
1 2 3 4
9 10 5
8 6
7
当n=5时,输出:
1 2 3 4 5
12 13 14 6
11 15 7
10 8
9
程序运行时,要求用户输入整数n(3~20)
程序输出:方阵的上三角部分。
要求格式:每个数据宽度为4,右对齐。
#include <stdio.h>
#define NUM 15
int main()
{
int arr[NUM][NUM] = {0};
int num = 1;
int index1 = 0;
int index2 = 0;
int right = NUM;
int bottom = NUM;
int top = 0;
while (top < bottom)
{
// 往右走
while (index2 < right)
{
arr[index1][index2++] = num++;
}
index1 += 1;
index2 -= 2;
// 往下走
while (index1 < bottom)
{
arr[index1++][index2--] = num++;
}
index1 -= 2;
index2 += 1;
// 往上走
while (index1 > top)
{
arr[index1--][index2] = num++;
}
index1 += 1;
index2 += 1;
right -= 2;
bottom -= 2;
top += 1;
}
for (index1 = 0; index1 < NUM; index1++)
{
for (index2 = 0; index2 < NUM-index1; index2++)
{
printf ("%4d", arr[index1][index2]);
}
printf ("\n");
}
return 0;
}