Welcome to our deep dive into C 2D Arrays! In this lesson, we'll explore this powerful data structure that's essential for handling multi-dimensional data. Let's start with the basics and gradually move towards advanced examples. 📝
A 2D array, also known as a matrix, is an array of arrays. It consists of elements arranged in rows and columns, much like a table. Each element is accessed using two indices: the first for the row and the second for the column.
To declare a 2D array in C, we first specify its number of rows and columns. Here's the general syntax:
dataType arrayName[rows][columns];Let's create a simple 3x3 2D array of integers:
#include <stdio.h>
int main() {
int matrix[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Accessing elements
printf("%d\n", matrix[0][0]); // Output: 1
printf("%d\n", matrix[1][2]); // Output: 6
return 0;
}Initializing a 2D array when you declare it is called compound literals. Here's an example:
#include <stdio.h>
int main() {
int matrix[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Accessing elements
printf("%d\n", matrix[0][0]); // Output: 1
printf("%d\n", matrix[1][2]); // Output: 6
return 0;
}You can perform various operations on 2D arrays, such as iterating through them, finding minimum or maximum values, and more. Here's an example of finding the minimum value in a 2D array:
#include <stdio.h>
void findMin(int matrix[3][3]) {
int min = matrix[0][0];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (matrix[i][j] < min) {
min = matrix[i][j];
}
}
}
printf("Minimum value: %d\n", min);
}
int main() {
int matrix[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
findMin(matrix);
return 0;
}What is a 2D array in C?
What is the general syntax for declaring a 2D array in C?