定一个正整数n,输出如下 n n “之字形”方阵。
例: 8 8 方阵。
C语言实现
#include<stdio.h>
#define x 100
int main(void)
{
int n,i=0,j=0,m=1;
scanf_s("%d", &n);//输入多少行
int a[x][x] = {1};
while (1)
{
if (m < (n * (n - 1) / 2 )+ n)
{
j++;
}
else
{
i++;
}
m++;
if (m > n * n)
break;
a[i][j] = m;
do {
i++;
j--;
m++;
if (m > n * n)
break;
a[i][j] = m;
if (m <=(n * (n-1) / 2) + n)
{
if (j == 0)
break;
}
else
{
if (i == n-1)
break;
}
} while (1);
if (m < (n * (n - 1) / 2 )+ n)
{
i++;
}
else
{
j++;
}
m++;
if (m > n * n)
break;
a[i][j] = m;
do {
i--;
j++;
m++;
if (m > n * n)
break;
a[i][j] = m;
if (m <=(n * (n - 1) / 2) + n)
{
if (i == 0)
break;
}
else
{
if (j == n-1)
break;
}
} while (1);
}
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
printf("%d\t", a[i][j]);
printf("\n");
}
return 0;
}