๐ C 2D Arrays – Working with Multidimensional Arrays
A 2D array in C is an array of arrays. It is a collection of data elements organized in a grid-like structure, which can be thought of as a table with rows and columns. 2D arrays are commonly used to represent matrices or tables of data.
๐น Declaring and Initializing a 2D Array
To declare a 2D array, you specify the number of rows and columns. The declaration looks similar to that of a 1D array, but with two dimensions.
๐ Example 1: Declaring a 2D Array
Here’s an example of how to declare a 2D array of integers:
#include <stdio.h> int main() { int matrix[2][3]; // Declaring a 2D array with 2 rows and 3 columns matrix[0][0] = 1; // Assigning value to the first element matrix[0][1] = 2; // Assigning value to the second element matrix[0][2] = 3; // Assigning value to the third element printf("Element at row 1, column 1: %d\n", matrix[0][0]); return 0; }
๐น Initializing a 2D Array
You can initialize a 2D array at the time of declaration by specifying values for each element. You can also omit the size of one dimension, and the compiler will infer it from the initialization.
๐ Example 2: Initializing a 2D Array
Here’s an example of initializing a 2D array:
#include <stdio.h> int main() { int matrix[2][3] = {{1, 2, 3}, {4, 5, 6}}; // Initializing a 2D array printf("Element at row 1, column 1: %d\n", matrix[0][0]); printf("Element at row 2, column 3: %d\n", matrix[1][2]); return 0; }
๐น Accessing Elements of a 2D Array
To access an element in a 2D array, you use two indices: one for the row and one for the column. The first index refers to the row, and the second refers to the column.
๐ Example 3: Accessing Elements of a 2D Array
In this example, we access each element of the 2D array and print it:
#include <stdio.h> int main() { int matrix[2][3] = {{1, 2, 3}, {4, 5, 6}}; // Accessing and printing each element using nested loops for (int i = 0; i < 2; i++) { for (int j = 0; j < 3; j++) { printf("Element at row %d, column %d: %d\n", i + 1, j + 1, matrix[i][j]); } } return 0; }
๐ฏ Key Points about 2D Arrays
- A 2D array is an array of arrays, with two dimensions: rows and columns.
- Elements in a 2D array are accessed using two indices: one for the row and one for the column.
- The size of a 2D array can be defined during declaration, or it can be inferred if initialized.
- 2D arrays are commonly used to represent tables, grids, or matrices.
๐ก Practice Challenge
Try modifying the number of rows and columns in the 2D array. Add loops to traverse and print the elements in a different way. Experiment with storing different types of data (e.g., floating-point numbers) in a 2D array!