Reputation: 1
This is a magic square problem, the size of the magic square n should be inputed as a command line argument. n has to be a odd number. The expected output should be like this. My problem is that when I try to execute the code, it generates a bunch of 0s.
I am a C beginner and I hope someone can help me with my problem. Thank you very much! I appreciate your help!
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int n = atoi(argv[1]);
int magic[n+1][n+1];
if(argc == 2)
{
for(int i = 0; i < n; i++)
{
for(int j = 0; j < n; j++)
{
magic[i][j] = 0;
}
}
int i =0 ;//row
int j= n / 2; //column
for ( int k = 1; k <= n*n; k++ )
{
magic[j][i] = k;
if(magic[j][i] == 0) //if the spot is empty
{
if (j == 0 && i == 0)
{
j--;//go up one level
i--; //go left
}
else
{
if(j == 0) //if it's on the first row
j = n - 1;
else
j--;
if (i == 0) //if it's on the left column
i = n - 1;
else
i--;
}
}
else //if the spot is not empty
{
j = j + 2;
i++;
}
}
}
for(int x=0; x<n; x++)
{
for(int y=0; y<n; y++)
printf("%3d", magic[x][y]);
printf("\n");
}
return 0;
}
Upvotes: -2
Views: 736
Reputation: 134
You cannot use variables to declare the size of an array
int magic[n+1][n+1];
You can:
1) Look up how to dynamically allocate arrays, or
2) Use a vector
Also, I don't think this is causing a problem now but
int n = atoi(argv[1]);
does not check to make sure that argv[1] contains numerical characters which may cause problems for you later.
Upvotes: -1