Apr 14, 20232D Arrays in C Tutorial 5Iterating through a 2D Array
William Huynh βΈ± 2 min read
Iterating through a 2D Array π
Preface πΆ
Whats the point of storing stuff in an array if we can access them all? Here we will learn how to iterate through a 2D array.
Getting Started π
To iterate through a 2D array you need:
- A variable representing the row index
- A variable representing the column index
- A nested for-loop!
Remember that a nested for loop is a loop within a loop!
So again, lets say we have the following array.
int my_array[2][4] = {
{1, 2, 3, 4}, // First row
{5, 6, 7, 8} // Second row
};
How would we iterate through the elements and print them out?
Well lets do it!
int row, col;
for (row = 0; row < 2; row++) {
for (col = 0; col < 4; col++) {
printf("%d ", myArray[row][col]);
}
printf("\n");
}
- The first loop runs through each row of the array, starting with row 0
- Then for that specific row, the second for loop, runs through every column
- Then for each column, we just print out the element!
The result will be:
1, 2, 3, 4, 5, 6, 7, 8
And thats all!
Congratulations, you are now a 2D Array King!