Display spiral matrix in C

258 Views Asked by At

I'm currently stuck at this point. I have to create a user defined 2 dimensional array that will go from 1 to N*N in a spiral form that starts from center and goes left.

So far I managed to print out the array, but I cannot figure out how to make it go spiral.

This is what I came up with, that doesn't work. Help would be much appreciated.

PS. I'm new to C.

#include <stdio.h>
#include <stdlib.h>

int N, i, j, x=0;

void spiral()
{
   int array[N][N];
   int k = 0, l = 0; // k = columns , l = rows
   int last_row = N - 1, last_column = N - 1;

   for (i = k; i <= last_column; i++)
   {
        k--;
        printf("%d ", array[k][j]);
   }

   for (j = l; i <= last_row; j++)
   {
        last_column++;
        printf("%d ", array[i][last_column]);
   }

   printf("\n");
}

int main()
{
    scanf("%d", &N);
    int array[N][N];
    spiral();

    for (i = 0; i < N; i++) //columns
    {
        for (j = 0; j < N; j++) //rows
        {
            x++;
            printf("%2d ", x);
        }

        printf("\n");
    }
}
0

There are 0 best solutions below