My problem is about a square array. I have a dynamic array in order to fill with numbers from 1 to N starting at 'the center' and spiralling out. If I have an array 6x6, I need to fill it in the way shown in the picture. If I have an array with an even number of cells in each direction, I need pick out a square in my array, and begin to count with the first element in a square. But if I have an array with an odd number of cells, I need to pick out a center of the array.
My main problem is to think of an algorithm which can help me to reach my "center". This is my code which I use for creating and printing my array:
#include <stdlib.h>
#include <stdio.h>
#include <malloc.h>
int** create_array(int, int);
void fill(int **, int, int);
void print_my_array(int**, int, int);
void print_my_array(int** , int , int );
int main() {
int **a, x, y;
printf("Enter x: ");
scanf("%d", &x);
printf("Enter y: ");
scanf("%d", &y);
a = create_array(x, y);
fill(a, x, y);
print_my_array(a, x, y);
return 0;
}
int** create_array(int rows, int cols) {
int **arr=NULL,i;
if (!(arr = (int**)malloc(rows*sizeof(int*)))) {
printf("Error");
exit(0);
}
for ( i = 0; i <rows; i++){
if (!(arr[i] = (int*)malloc(cols*sizeof(int)))) {
printf("Error");
exit(0);
}
return arr;
}
return arr;
}
void fill(int **arr, int x, int y) {
//HELP
}
void print_my_array (int** array, int x, int y)
{
int i, j;
for(i=0;i<x;i++)
{
for(j=0;j<y;j++)
{
printf("%d ", array[i][j]);
}
printf("\n");
}
printf("\n");
}
The center of the
nxn
array is(floor((n-1)/2),floor((n-1)/2))
[0 indexing]. But we will solve it differently. If n is even then it will end inSo for even n it always ends in [0,n-1]. Now what you will do to fill it up?
You know the numbers will be
n*n, n*n-1,n*n-2...2,1
.Similarly for n odd
Hope you get what we want to do from these pics?
Code