set of directions for an array to follow in C

So for my coding class (in C), we had to write a program that would fill a square of N >=4 elements in a certain manner (from left to right and then down and then right to left to go up and end at the origin).

After a while, and getting a solution with layers repeating the set of instructions for each circle we get this program:

#include <stdio.h>

#define N 4



int main(void){
    int map[N][N];
    int dirs[4][2] = {
            {0, 1},
            {1, 0},
            {0, -1},
            {-1, 0}

    };
    for (int layer=0; layer < (N+1)/2; layer++){
        // for each layer the starting point is (layer, layer)
        // for each layer and each direction the number of repeat is N - layer*2 -1
        int x=layer, y=layer;
        int number = 1;
        map[x][y] = number; // in case of N is odd
        for (int dir=0; dir < 4; dir ++){
            for (int i=0; i<N-layer*2-1; i++){
                map[x][y] = number;
                number ++;
                x = x + dirs[dir][0];
                y = y + dirs[dir][1];
            }
        }
    }

    printf("Final map is: \n");
    for (int i = 0; i < N; i++){
        for (int j = 0; j < N; j++){
            printf("%4d ", map[i][j]);
        }
        printf("\n");
    }

    return 0;
}



Output:

Final map is: 
   1    2    3    4 
  12    1    2    5 
  11    4    3    6 
  10    9    8    7 

Process finished with exit code 0

But I don't understand why do we put the supposed last instruction {0,1} (meaning go up 1 element and stay on said column) as the first instruction, considering we start counting from 1 and end up at 4.



Read more here: https://stackoverflow.com/questions/66280530/set-of-directions-for-an-array-to-follow-in-c

Content Attribution

This content was originally published by Jorge Ávila Balmaceda at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: