You are using a version without Ads of this website. Please, consider donating:

### for loop & array

 ``12345678910111213141516171819202122232425262728293031323334353637`` `````` #include using namespace std; # define width 5 # define height 6 int yo [width] [height]; int x,y; int main() { for (x=0; x

Hi, I was taking one of the examples and altering it. After the for loop, I assign the value of x to yo[x][y]. 0 to 4 repeats itself six times because [y] (that is, height) has the value of 6. In this case the numbers should also repeat five times again because [x] (that is, width) has a value of 5. But it does not do so. Why? Please correct me if my analysis is wrong.

Thanks
Last edited on
 In this case the numbers should also repeat five times again because [x] (that is, width) has a value of 5.

This is not true.

What's happening is you are filling a 5x6 array with data, and printing that data. The array conceptually looks like this:

 ``123456789`` `````` X 0 1 2 3 4 +_____________ 0 | 1 | Y 2 | data 3 | 4 | 5 |``````

You are filling each element in the array so that the element = its x position. So the filled array conceptually looks like this:

 ``123456789`` `````` X 0 1 2 3 4 +_______________ 0 | 0 1 2 3 4 1 | 0 1 2 3 4 Y 2 | 0 1 2 3 4 3 | 0 1 2 3 4 4 | 0 1 2 3 4 5 | 0 1 2 3 4``````

You are then printing this array in column major order... that is:
column 0, row 0
column 0, row 1
column 0, row 2
...
column 0, row 5
column 1, row 0
column 1, row 1
...
etc

The values repeat 6 times because you are printing the first column of data... all of which is the same value.

It does not repeat an additional 5 times because each column has different data.
Topic archived. No new replies allowed.