【发布时间】:2018-11-15 18:11:20
【问题描述】:
我想编写一个代码,从用户那里获取整数 n,并在不使用数组的情况下以从 1 到 n*n 的螺旋模式打印数字。 output for entering 5
input3
output:
1 2 3
8 9 4
7 6 5
你对如何编写这段代码有什么建议吗?
编辑: 这是使用数组的代码:
#include <stdio.h>
int main(){
/*declaration of the variables*/
int i, j, ascendingNumbers;
int leftAndTop, rightAndBottom;
int size;
scanf("%d", &size);
int matrix[size][size];
leftAndTop = 0;
rightAndBottom = size - 1;
ascendingNumbers = 1;
/*filling the array*/
for(i = 1; i <= size/2; i++, leftAndTop++, rightAndBottom--){
/*left to right*/
for(j = leftAndTop; j <= rightAndBottom; j++, ascendingNumbers++){
matrix[leftAndTop][j] = ascendingNumbers;
}
/*top to bottom*/
for(j = leftAndTop + 1; j <= rightAndBottom; j++, ascendingNumbers++){
matrix[j][rightAndBottom] = ascendingNumbers;
}
/*right to left*/
for(j = rightAndBottom-1; j >= leftAndTop; j--, ascendingNumbers++){
matrix[rightAndBottom][j] = ascendingNumbers;
}
/*bottom to top*/
for(j = rightAndBottom - 1; j >= leftAndTop+1; j--, ascendingNumbers++){
matrix[j][leftAndTop] = ascendingNumbers;
}
}
/*fill the center for odd size*/
if(size % 2){
matrix[leftAndTop][j + 1] = ascendingNumbers;
}
/*print*/
for(i = 0; i < size; i++){
for(j = 0; j < size; j++){
printf("%d ", matrix[i][j]);
}
printf("\n");
}
return 0;
}
【问题讨论】:
-
不,这个问题应该用 for 和 while 循环来解决。
-
我已经使用数组编写了代码,但是我需要在没有数组的情况下编写它,我无法这样做。
-
我编辑了帖子并添加了代码
标签: c for-loop while-loop spiral