Reputation: 1
As a beginner for c++, I'm using the C++ primer as my textbook. I just got to the multidimensional array part. This is the code in the book about assigning values to such an array, but I don't quite understand..
constexpr size_t rowCnt = 3, colCnt = 4;
int ia[rowCnt][colCnt];
for (size_t i = 0; i != rowCnt; ++i) {
for (size_t j = 0; j != colCnt; ++j) {
ia[i][j] = i * colCnt + j;
}
}
How does ia[i][j] = i * colCnt + j;
assign value to the array?
Upvotes: 0
Views: 902
Reputation: 19
From your code
int ia[rowCnt][colCnt];
This is much the same like thi int is[3][4]; This mean that your array can hold 3 items (values) in row and 4 in the column.
Then you used a for loops to loop through every index of the array, which you use nasted loop, so the first loop is for the row, and the second for the column.
In the first loop
for(size_t i = 0; i != rowCnt; i++)
So this first loop is for looping through and incrementing the value of i untill it is rowCnt; (3)
Same goes for the second loop.
for(size_t j = 0; j != colCnt; j++)
Also remember that, the innner loop will always be executed completely while the utter loop is executed once.
So this mean when i = 0 and j = 0; ai[i][j] = i * colCnt + j;
which means.
In the first row and the the first column, give it the value of
i * colCnt + j;
So it keeps on like that until all the values are field out
.
I'm not sure if you understand, but I hope I've answered your question.
Upvotes: 0
Reputation: 27478
So you have an array of three rows, each row consists of array of four columns.
To address the first column in the first row as "ia[0][0]" to address the second column in the first row use "ia[0][1]". To address the last column in the last row use "ia[2][3]".
The compiler needs to calculate the address of the row you require using the "i" variable: "ia[i]" then calculate the position of the column within that row using the "j" variable: "ia[i][j]".
Upvotes: 1
Reputation: 161
To access element number "x" in an array you call array[x] right? And to assign a value to that index you call array[x] = "something".
In a multidimensional array, the element at "x" is another array, so:
ai[i][j] becomes (ai array at index i)[j] .
I hope that makes sense.
What is then assigned on the right side of the equal sign is irrelevant, in your case because of the loops you'll get something like
0, 1, 2
3, 4, 5
6, 7, 8
Upvotes: 3