0
int game()
{
    int n;
    cout << "enter an odd number: ";
    cin >> n;
    int MagicSquare[n][n];  // It says that the expression must have a constant type? 
    int newRow,newCol;
    int i = 0;
    int j = n / 2;

    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < n; j++) 
        {
            MagicSquare[i][j] = 0;
        }
    }

    for (int value = 1; value <= n*n; value++)
    {
        MagicSquare[i][j] = value;
        newRow = (i + 1) % n;
        newCol = (j + 1) % n;

        if (MagicSquare[newRow][newCol] == 0)
        {
            i = newRow;
            j = newCol;
        }
        else
        {
            i = (i - 1 + n) % n;
        }
    }
    for (int x = 0; x<n; x++)
    {
        for (int y = 0; y<n; y++)
        cout << MagicSquare[x][y] << " "<<endl;
    }
}
4
Contributors
6
Replies
27
Views
2 Years
Discussion Span
Last Post by tinstaafl
0

// It says that the expression must have a constant type?

perhaps you are working with pre standard c++ in which array size must be a constant value.variables are not accepted.

After its standardization , array size can be specified with a variable.

Edited by Learner010

0

C++ does not support them as can be read in the standard (8.3.4.1).

thanks.i get it.you were correct.

An array bound must be a constant expression. for variable bound , there are vectors.
But i think GCC Compiler runs the code without throughing any error or warning.

0

You could use the new operator, but that comes with more baggage, like security concerns and manual disposal.

0

i think new operator is associated with pointers(however array items can be accessed using a pointer).In this case i think new operator is good choice.

if OP is using new operator then he might also consider using delete[]. otherwise there would memory leak.correct ?

Edited by Learner010

0

Yes that is part of what my message was getting at. There are good points and bad points to consider.

Edited by tinstaafl

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.