for loop & array

Write your question here.

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
29
30
31
32
33
34
35
36
37


#include <iostream>
using namespace std;

# define width 5
# define height 6



int yo [width] [height];


int x,y;


int main()
{

 for (x=0; x<width; x++)
 for (y=0;y<height; y++)
            
        {
            
          yo[x][y]= x;
            
          cout << yo[x][y]<< endl;
            
        }
    
   
  
    return 0;
}




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:

1
2
3
4
5
6
7
8
9
            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:

1
2
3
4
5
6
7
8
9
              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.