This tutorial explains two-dimensional arrays in C, which store elements in a matrix-like structure with rows and columns. It covers declaration, initialization, accessing elements, and practical examples such as matrix input, display, and addition.
1. What is a Two-Dimensional Array
- A two-dimensional array stores elements in rows and columns.
- Each element is accessed using two indices:
[row][column]. - Often used to represent matrices or tables.
2. Syntax
data_type array_name[rows][columns];
data_type – type of elements (int, float, char, etc.)array_name – name of the arrayrows – number of rowscolumns – number of columns
Example: Declaration
int matrix[3][3]; // 3x3 integer matrix
float prices[2][4]; // 2x4 float matrix
3. Array Initialization
Method 1: During Declaration
int matrix[2][3] = {
{1, 2, 3},
{4, 5, 6}
};
Method 2: Partial Initialization
int matrix[2][3] = {
{1, 2},
{4}
}; // remaining elements = 0
4. Accessing Array Elements
matrix[0][1] = 10; // sets element at first row, second column
printf("%d", matrix[1][2]); // prints element at second row, third column
5. Example Program: Input and Display 2D Array
#include <stdio.h>
int main() {
int rows, cols, i, j;
printf("Enter number of rows: ");
scanf("%d", &rows);
printf("Enter number of columns: ");
scanf("%d", &cols);
int matrix[rows][cols];
// Input elements
for(i = 0; i < rows; i++) {
for(j = 0; j < cols; j++) {
printf("Enter element [%d][%d]: ", i, j);
scanf("%d", &matrix[i][j]);
}
}
// Display elements
printf("Matrix:\n");
for(i = 0; i < rows; i++) {
for(j = 0; j < cols; j++) {
printf("%d\t", matrix[i][j]);
}
printf("\n");
}
return 0;
}
Sample Output:
Enter number of rows: 2
Enter number of columns: 3
Enter element [0][0]: 1
Enter element [0][1]: 2
Enter element [0][2]: 3
Enter element [1][0]: 4
Enter element [1][1]: 5
Enter element [1][2]: 6
Matrix:
1 2 3
4 5 6
6. Example Program: Sum of Two Matrices
#include <stdio.h>
int main() {
int r, c, i, j;
printf("Enter rows and columns: ");
scanf("%d %d", &r, &c);
int A[r][c], B[r][c], sum[r][c];
// Input matrix A
printf("Enter elements of matrix A:\n");
for(i = 0; i < r; i++)
for(j = 0; j < c; j++)
scanf("%d", &A[i][j]);
// Input matrix B
printf("Enter elements of matrix B:\n");
for(i = 0; i < r; i++)
for(j = 0; j < c; j++)
scanf("%d", &B[i][j]);
// Calculate sum
for(i = 0; i < r; i++)
for(j = 0; j < c; j++)
sum[i][j] = A[i][j] + B[i][j];
// Display sum
printf("Sum of matrices:\n");
for(i = 0; i < r; i++) {
for(j = 0; j < c; j++)
printf("%d\t", sum[i][j]);
printf("\n");
}
return 0;
}
7. Key Points to Remember
- Two-dimensional arrays store data in rows and columns
- Indexing starts from 0
- Can be used for matrices, tables, and grids
- Initialization can be full, partial, or runtime input