displaying an array with some loops
Aug 16, 2013 at 10:21am UTC
hello, I don't know what I'm doing wrong here, but it must be some obvious stupid mistake, I am trying to learn how to use arrays and made this very simple program to display:
123
456
789
but I am getting:
124
452
029
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
#include <iostream>
using namespace std;
int main()
{
int array[2][2];
array[0][0] = 1;
array[0][1] = 2;
array[0][2] = 3;
array[1][0] = 4;
array[1][1] = 5;
array[1][2] = 6;
array[2][0] = 7;
array[2][1] = 8;
array[2][2] = 9;
for (int row = 0; row <3; row++)
{
for (int col = 0; col < 3; col++)
{
cout << array[row][col];
}
cout << endl;
}
return 0;
}
if someone could tell me what I'm doing wrong I would appreciate it, thank you.
Aug 16, 2013 at 10:24am UTC
You're defining a 2 x 2 array:
int array[2][2];
This means that the valid indices are 0 and 1.
If you want a 3 x 3 array, you need to declare it as:
int array[3][3];
Aug 16, 2013 at 10:29am UTC
thanks a lot
Aug 16, 2013 at 1:49pm UTC
You're welcome.
Topic archived. No new replies allowed.