Home>

The program I want to write is a spiral from inside to outside,
In the program below, you will end up with a swirl from outside to inside.
Enter the numbers in reverse order from the larger one so that the last place is 1
I know that the numerical value n to be entered starts from the maximum value (x*y),
I can't code it.
I am a beginner, thank you.

#include<stdio.h>
int main(void) {
    #define N 6
    int a[N+2][N+2] = {0};
    int p[4] = {1,0,-1,0 };
    int q[4] = {0,1,0,-1 };
    for (int i = 0;i<= N;i++)
        a[0][i] = a[N+1][i+1] = a[i][0] = a[i+1][N+1] = 1;
    for (int x = 1, y = 1, t = 0, i = 1;i<= N*N;x += p[t], y += q[t])
        if (a[y][x] = i++, a[y + q[t]][x + p[t]]&&++t == 4) t = 0;
    for (int i = 1;i<= N;i++, putchar('\n'))
        for (int j = 1;j<= N;j++) printf("%4d", a[i][j]);
    return 0;
}

c language

c
  • Answer # 1

    if (a[y][x] =i++...

    Do this ↑

    if (a[y][x] =N*N+1-i++...

  • Answer # 2

    iShould I just reverse the order?

    -for (int x = 1, y = 1, t = 0, i = 1;i<= N*N;x += p[t], y += q[t])
    + for (int x = 1, y = 1, t = 0, i = N * N;i >= 1;x += p[t], y += q[t])
    -if (a[y][x] = i++, a[y + q[t]][x + p[t]]&&++t == 4) t = 0;
    + if (a[y][x] = i--, a[y + q[t]][x + p[t]]&&++t == 4) t = 0;

  • Answer # 3

    if (a[y][x] = N*N+1-i++, a[y + q[t]][x + p[t]]&&++t == 4) t = 0;
    There may be a hand.

    To put it aside, I think it's better not to stuff it with comma operators. There is no merit just to confuse the reader.

    {
        a[y][x] = N*N+1-i++;
        if (a[y + q[t]][x + p[t]]&&++t == 4) t = 0;
      }