Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
What is a two-dimensional array in C language?
A two-dimensional array in C is a collection of elements arranged in rows and columns, forming a matrix-like structure. It is essentially an array of arrays, where each element is identified by two indices: row index and column index.
Syntax
datatype array_name[row_size][column_size];
Example: int matrix[3][4]; declares a 2D array with 3 rows and 4 columns.
Memory Layout
Two-dimensional arrays are stored in row-major order in memory. Here's how a 2x3 array looks −
Initialization Methods
Two-dimensional arrays can be initialized in two ways −
Method 1: Compile-time Initialization
#include <stdio.h>
int main() {
int a[3][3] = {10, 20, 30, 40, 50, 60, 70, 80, 90};
int i, j;
printf("Elements of the array are:<br>");
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
printf("%d\t", a[i][j]);
}
printf("<br>");
}
return 0;
}
Elements of the array are: 10 20 30 40 50 60 70 80 90
Method 2: Runtime Initialization
This example shows how to read values from the user at runtime −
#include <stdio.h>
int main() {
int a[2][2] = {{1, 2}, {3, 4}}; // Pre-initialized for demo
int i, j;
printf("Elements of the array are:<br>");
for (i = 0; i < 2; i++) {
for (j = 0; j < 2; j++) {
printf("%d\t", a[i][j]);
}
printf("<br>");
}
return 0;
}
Elements of the array are: 1 2 3 4
Example: Matrix Operations
This example demonstrates addition and multiplication of two 2D arrays −
#include <stdio.h>
int main() {
int A[2][2] = {{1, 2}, {3, 4}};
int B[2][2] = {{5, 6}, {7, 8}};
int sum[2][2], product[2][2];
int i, j;
/* Calculate sum */
for (i = 0; i < 2; i++) {
for (j = 0; j < 2; j++) {
sum[i][j] = A[i][j] + B[i][j];
}
}
/* Calculate element-wise product */
for (i = 0; i < 2; i++) {
for (j = 0; j < 2; j++) {
product[i][j] = A[i][j] * B[i][j];
}
}
printf("Sum array:<br>");
for (i = 0; i < 2; i++) {
for (j = 0; j < 2; j++) {
printf("%d\t", sum[i][j]);
}
printf("<br>");
}
printf("Product array:<br>");
for (i = 0; i < 2; i++) {
for (j = 0; j < 2; j++) {
printf("%d\t", product[i][j]);
}
printf("<br>");
}
return 0;
}
Sum array: 6 8 10 12 Product array: 5 12 21 32
Key Points
- Elements are accessed using
array_name[row_index][column_index] - Both indices start from 0
- Memory is allocated in row-major order
- Nested loops are commonly used to traverse 2D arrays
Conclusion
Two-dimensional arrays in C provide an efficient way to store and manipulate tabular data. They are essential for matrix operations, image processing, and any application requiring grid-based data storage.
