bluetickk
bluetickk

Reputation: 689

For loop logic error?

void GameBoard::print(const GameBoard& computerBoard)
{
Grid[0][0] = '1';
Grid[0][1] = '2';
Grid[1][0] = '3';

int i, j;
int sides = SIZE;

cout << "        Your bombs:                    Your navy:" << endl << endl;

for(i=0; i<SIZE; i++)
{
    // prints your bombs
    cout << sides << "  ";
    for(j=0; j<SIZE; j++)
    {
        cout << computerBoard.Grid[i][j] << "  ";
    }
    cout << "    ";

    // prints your ships
    cout << sides << "  ";
    for(j=0; j<SIZE; j++)
    {
        cout << Grid[i][j] << "  ";
    }
    cout << endl << endl;
    sides--;
}

j = 0;
cout << "\n   ";

for(i=0; i<SIZE; i++)
{
    j = i + 'A';
    cout << (char)j << "  ";
}
cout << "       ";

for(i=0; i<SIZE; i++)
{
    j = i + 'A';
    cout << (char)j << "  ";
}
cout << endl << endl;

}

I am constructing a game like battleship, and need to change the for loop to read..

for(i=8;i>0;i--)

why does this produce an error?

Sorry if this doesnt make sense, Grid[0][0] should be on the bottom left, but it is currently at the top left.

Upvotes: 1

Views: 188

Answers (1)

schnaader
schnaader

Reputation: 49719

I guess what you want is something like

for(i=SIZE-1; i>=0; i--)

because this is equivalent to

for(i=0; i<SIZE; i++)

both of these go from 0..SIZE-1 while

for(i=SIZE; i>0; i--)

goes from 1..SIZE (and so if you access an array of length SIZE using arr[i], will produce an error).

Upvotes: 8

Related Questions