All explanations I’ve heard from teachers AND from the few textbooks I’ve read have such a convoluted explanation of this data structure.
To put it simply, a 2-Dimensional array is nothing more than a single array that contains multiple other arrays. That’s it!
|
|
When you arrange it like this, you see the tabular structure everyone talks about.
The other thing to know is how to loop through such an array. You’ll need exactly 2 loops for this. One loop to select each array in array_2d
; the other to go through the items in each array of array_2d
.
Think of it this way: when you loop through a regular ol’ array, you loop through each individual element, right?
|
|
Now, if we let:
|
|
and we also let:
|
|
then looping through a 2-dimensional array is no different.
At any given moment, our loop variable will hold a
, b
, or c
, as shown below:
|
|
It is at this moment you require a second loop if you want to access each element in a
, b
, or c
.
|
|