Outputing multidimentional array using for loops

In the code that I am working on I am generating random numbers and assigning them a 2d array. But when I output the array in a separate nest of for loops the values are incorrect, but if I output the array in the same nest of for loops the values are correct





int spot[4][4];
int range[] = {1,16,31,46,61}, held[4];


void Generate()
{

for (int y =0; y<=4; y++)
{
for ( int x =0; x<=4; x++)
{
spot[x][y] = (range[x] + rand() % 15);
spot[2][2] = 0;
}

cout << setw (5)<<spot[x][y];
}
cout<<endl;
}

cout<<endl;

for (int a =0; a<=4; a++)
{
for ( int b =0; b<=4; b++)
{
cout<<spot[b][a] << endl;

}


}
}
That is because in your seperate nested loop, you are accessing the elements of the array wrong. You should be accessing spot[a][b] not spot[b][a]
Hey thanks for the help but when I tried your solution the problem did not go away, the array listed horizontally instead of vertically. The problem in the code is that in the separate nested loop when I output the array the last number in the column changes into the first number for the next row.
Your for loops overstep the bounds of the array.

Use the < operator in the end conditions not <=.

In the spot array, the last legal subscripts are [3][3], because arrays start at 0.

HTH
Topic archived. No new replies allowed.