2d Arrays & Nested Loops
Lesson 25Author : Afrixi
Last Updated : January, 2023
A 2D array, also known as a two-dimensional array, is an array that consists of elements organized into rows and columns. Each element in the 2D array can be accessed using two indices, one for the row and one for the column. A 2D array can be thought of as a table, where each row represents a different set of values and each column represents a different property of those values.
In C, a 2D array can be declared by specifying the number of rows and columns as follows:
int myArray[ROWS][COLUMNS];
where ROWS
and COLUMNS
are constants or variables representing the number of rows and columns, respectively.
To access an element in a 2D array, we use the following syntax:
myArray[rowIndex][columnIndex]
where rowIndex
and columnIndex
are the indices of the element we want to access.
We can also use nested loops to iterate through all the elements in a 2D array. Here’s an example of how to initialize a 2D array and print its elements using nested loops:
#include <stdio.h>
#define ROWS 3
#define COLUMNS 4
int main() {
int myArray[ROWS][COLUMNS] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLUMNS; j++) {
printf("%d ", myArray[i][j]);
}
printf("\n");
}
return 0;
}
This code declares a 2D array myArray
with 3 rows and 4 columns, and initializes it with some values. Then it uses nested for
loops to iterate through all the elements in the array and print them to the console. The outer loop iterates over the rows and the inner loop iterates over the columns. Finally, the program returns 0 to indicate successful execution.