
2D Arrays in C
A 2D array in C is essentially an array of arrays. It's a data structure that represents tabular data or matrices. In memory, a 2D array is stored in a contiguous block of memory, where elements are arranged in rows and columns.
datatype arrayName[rows][columns];
To declare a 2D array, you specify the data type and the dimensions (rows and columns) within square brackets. For example : This declares a 3x3 matrix of integers named matrix.
int matrix[3][3];
You can initialize the elements of a 2D array when you declare it.For example : This initializes a 3x3 matrix with specific values.
int matrix[3][3] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
You access elements using row and column indices.For example : matrix[0][0] accesses the element in the first row and first column.
int element = matrix[rowIndex][columnIndex];
Output :
Matrix:
1 2 3
4 5 6
7 8 9
Output :
Enter the number of row and column=2
2
Enter the 1st matrix=1
2
3
4
Enter the values of 2nd matrix=1
2
3
4
The matrix after sum=
2 4
6 8
Output :
Enter row & coloumn:2
2
Enter the value of matrix : 1
Enter the value of matrix : 2
Enter the value of matrix : 3
Enter the value of matrix : 4
Matrix after transpose :
1 3
s
2 4
Two-dimensional arrays in C are important for a variety of reasons :
Representation of Matrices and Tables : 2D arrays are essential for representing matrices, grids, and tables.
Image Processing : In graphics and image processing, images are represented as 2D arrays where each element corresponds to a pixel.
Game Development : Many games use 2D arrays to represent game boards, maps, and levels. This structure is crucial for implementing game logic and rendering scenes.
Data Storage and Retrieval : 2D arrays facilitate the storage and retrieval of data in a structured manner. For example, in database management, data can be stored in a tabular form using 2D arrays.
Algorithm Implementation : Many algorithms, such as dynamic programming and graph traversal algorithms, rely on 2D arrays for storing intermediate results and maintaining state information.
Understanding these fundamentals enables you to work effectively with 2D arrays in C, facilitating operations like matrix manipulations, image processing, and more.