My current exercise, as I am trying to grasp the basics of C is to create a magic square.
Here is the code of what seems to be a successful project:
Code:
int main(void)
{
short size, col, row, i;
printf("\nThis program creates a \"magic square\" of specified size.");
printf("\nThe size must be an odd number.");
printf("\nBeyond size 99 some numbers will have no space between.");
printf("\nEnter size: ");
scanf(" %d", &size);
short square[size][size]; /* Declare a two-dimensional array of size x size */
for (row = 0; row < size; ++row) /*******************************************/
for (col = 0; col < size; ++col) /* Give every element in the array value 0 */
square[row][col] = 0; /*******************************************/
row = 0; /***************************************/
col = size / 2; /* Place the first number in the array */
square[row][col] = 1; /***************************************/
for (i = 2; i <= size * size; ++i)
{
if (--row < 0) /*****************************************************/
row = (size - 1); /* Evaluate the indexes to the next position, */
/* wrapping around to the opposite side, everytime */
if (++col > (size - 1)) /* an index goes outside the bounds of the array. */
col = 0; /*****************************************************/
if (square[row][col] != 0) /* Check if a number is already placed in the new position */
{
if (++row > (size - 1)) /***********************************************/
row = 0; /* Evaluate indexes to the previous position, */
/* wrapping to the opposite side, everytime an */
if (--col < 0) /* index goes outside the bounds of the array */
col = (size - 1); /***********************************************/
while (square[row][col] != 0) /*****************************************/
if (++row > (size - 1)) /* Evaluate indexes to the first 0 value */
row = 0; /* element, below the last placed number */
} /*****************************************/
square[row][col] = i; /* Place the next number in the array */
}
for (row = 0; row < size; ++row)
{
printf("\n");
for (col = 0; col < size; ++col)
printf("%5d", square[row][col]);
}
return 0;
}
Since I am at a novice level, I tend to complicate my life and thus my code. So I was wondering if there is another, more simple way, to write such project. No need to write me a whole program, just a few pointers of what could have done better.
When I grow up, my priorities when writing something should be, speed, memory usage, and readability of code (not in random order). Having that in mind and assuming that no input value bigger than 99 will be used, is the use of short int, instead of int correct?
Thank you very much for your time and your valuable advices