Introduction
Two-dimensional arrays in C are arrays of arrays, creating a table-like structure with rows and columns. They are essential for representing matrices, grids, tables, and other data structures that require organization in two dimensions. Understanding 2D arrays is crucial for working with mathematical computations, game boards, image processing, and tabular data.
Key Concepts
Matrix Structure: Organized in rows and columns Index Notation: array[row][column] for accessing elements Memory Layout: Stored in row-major order in memory Nested Loops: Commonly used for processing 2D arrays
Declaration and Initialization
Basic Declaration
#include <stdio.h>
int main() {
// Declaration with size specification
int matrix[3][4]; // 3 rows, 4 columns
float grades[5][3]; // 5 students, 3 subjects
char board[8][8]; // Chess board
return 0;
}
Initialization Methods
#include <stdio.h>
int main() {
// Method 1: Complete initialization
int matrix1[2][3] = {
{1, 2, 3},
{4, 5, 6}
};
// Method 2: Flat initialization
int matrix2[2][3] = {1, 2, 3, 4, 5, 6};
// Method 3: Partial initialization
int matrix3[3][3] = {
{1, 2}, // Rest filled with 0
{4, 5, 6},
{7} // Rest filled with 0
};
// Method 4: Let compiler determine first dimension
int matrix4[][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
return 0;
}
Accessing Elements
#include <stdio.h>
int main() {
int matrix[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Accessing individual elements
printf("Element at [0][0]: %d\n", matrix[0][0]); // 1
printf("Element at [1][2]: %d\n", matrix[1][2]); // 6
printf("Element at [2][1]: %d\n", matrix[2][1]); // 8
// Modifying elements
matrix[1][1] = 10;
printf("Modified element at [1][1]: %d\n", matrix[1][1]);
return 0;
}
Input and Output Operations
Reading User Input
#include <stdio.h>
int main() {
int rows = 2, cols = 3;
int matrix[2][3];
printf("Enter elements for %dx%d matrix:\n", rows, cols);
// Input using nested loops
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("Enter element [%d][%d]: ", i, j);
scanf("%d", &matrix[i][j]);
}
}
// Display the matrix
printf("\nMatrix:\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%4d ", matrix[i][j]);
}
printf("\n");
}
return 0;
}
Matrix Operations
Matrix Addition
#include <stdio.h>
int main() {
int rows = 2, cols = 2;
int matrix1[2][2] = {{1, 2}, {3, 4}};
int matrix2[2][2] = {{5, 6}, {7, 8}};
int result[2][2];
// Addition
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
result[i][j] = matrix1[i][j] + matrix2[i][j];
}
}
// Display result
printf("Matrix Addition Result:\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%4d ", result[i][j]);
}
printf("\n");
}
return 0;
}
Matrix Multiplication
#include <stdio.h>
int main() {
int matrix1[2][3] = {{1, 2, 3}, {4, 5, 6}};
int matrix2[3][2] = {{7, 8}, {9, 10}, {11, 12}};
int result[2][2] = {0}; // Initialize to 0
// Matrix multiplication
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
for (int k = 0; k < 3; k++) {
result[i][j] += matrix1[i][k] * matrix2[k][j];
}
}
}
// Display result
printf("Matrix Multiplication Result:\n");
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
printf("%4d ", result[i][j]);
}
printf("\n");
}
return 0;
}
Matrix Transpose
#include <stdio.h>
int main() {
int rows = 3, cols = 2;
int matrix[3][2] = {{1, 2}, {3, 4}, {5, 6}};
int transpose[2][3];
// Calculate transpose
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
transpose[j][i] = matrix[i][j];
}
}
printf("Original Matrix:\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%4d ", matrix[i][j]);
}
printf("\n");
}
printf("\nTranspose Matrix:\n");
for (int i = 0; i < cols; i++) {
for (int j = 0; j < rows; j++) {
printf("%4d ", transpose[i][j]);
}
printf("\n");
}
return 0;
}
Practical Applications
Student Grade Management
#include <stdio.h>
int main() {
int students = 3, subjects = 4;
float grades[3][4] = {
{85.5, 92.0, 78.5, 88.0}, // Student 1
{76.5, 89.0, 94.5, 82.0}, // Student 2
{90.0, 87.5, 91.0, 95.5} // Student 3
};
// Calculate and display averages
printf("Student Grade Report:\n");
printf("Student\tSub1\tSub2\tSub3\tSub4\tAverage\n");
for (int i = 0; i < students; i++) {
float total = 0;
printf("%d\t", i + 1);
for (int j = 0; j < subjects; j++) {
printf("%.1f\t", grades[i][j]);
total += grades[i][j];
}
printf("%.2f\n", total / subjects);
}
return 0;
}
Tic-Tac-Toe Game Board
#include <stdio.h>
void displayBoard(char board[3][3]) {
printf("\n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
printf(" %c ", board[i][j]);
if (j < 2) printf("|");
}
printf("\n");
if (i < 2) printf("-----------\n");
}
printf("\n");
}
int main() {
char board[3][3] = {
{' ', ' ', ' '},
{' ', ' ', ' '},
{' ', ' ', ' '}
};
// Simulate some moves
board[0][0] = 'X';
board[1][1] = 'O';
board[2][2] = 'X';
board[0][2] = 'O';
printf("Tic-Tac-Toe Board:");
displayBoard(board);
return 0;
}
Image Processing (Simple Example)
#include <stdio.h>
int main() {
int rows = 4, cols = 4;
int image[4][4] = {
{100, 120, 140, 160},
{110, 130, 150, 170},
{120, 140, 160, 180},
{130, 150, 170, 190}
};
printf("Original Image:\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%4d ", image[i][j]);
}
printf("\n");
}
// Apply brightness filter (add 50)
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
image[i][j] += 50;
if (image[i][j] > 255) image[i][j] = 255; // Clamp to max
}
}
printf("\nBrightened Image:\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%4d ", image[i][j]);
}
printf("\n");
}
return 0;
}
Searching and Sorting
Finding Maximum Element
#include <stdio.h>
int main() {
int matrix[3][3] = {
{12, 45, 23},
{67, 89, 34},
{56, 78, 91}
};
int max = matrix[0][0];
int max_row = 0, max_col = 0;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (matrix[i][j] > max) {
max = matrix[i][j];
max_row = i;
max_col = j;
}
}
}
printf("Matrix:\n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
printf("%4d ", matrix[i][j]);
}
printf("\n");
}
printf("\nMaximum element: %d at position [%d][%d]\n", max, max_row, max_col);
return 0;
}
Row and Column Sums
#include <stdio.h>
int main() {
int matrix[3][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
printf("Matrix:\n");
for (int i = 0; i < 3; i++) {
int row_sum = 0;
for (int j = 0; j < 4; j++) {
printf("%4d ", matrix[i][j]);
row_sum += matrix[i][j];
}
printf("| Sum: %d\n", row_sum);
}
printf("---------------------\n");
printf("Col:");
for (int j = 0; j < 4; j++) {
int col_sum = 0;
for (int i = 0; i < 3; i++) {
col_sum += matrix[i][j];
}
printf("%4d ", col_sum);
}
printf("\n");
return 0;
}
Memory Layout and Pointers
#include <stdio.h>
int main() {
int matrix[2][3] = {
{1, 2, 3},
{4, 5, 6}
};
printf("Matrix elements and their addresses:\n");
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
printf("matrix[%d][%d] = %d, address = %p\n",
i, j, matrix[i][j], (void*)&matrix[i][j]);
}
}
// Accessing as 1D array
printf("\nAccessing as 1D array:\n");
int *ptr = (int*)matrix;
for (int i = 0; i < 6; i++) {
printf("ptr[%d] = %d\n", i, ptr[i]);
}
return 0;
}
Best Practices
- Initialize Arrays: Always initialize arrays to avoid garbage values
- Bounds Checking: Ensure indices are within valid range
- Meaningful Names: Use descriptive variable names for rows and columns
- Consistent Loops: Use same variable names (i, j) consistently
- Memory Considerations: Be aware of memory usage for large arrays
Summary
Two-dimensional arrays provide a powerful way to work with tabular data in C. They are essential for matrix operations, game development, image processing, and data management. Understanding how to declare, initialize, access, and manipulate 2D arrays enables you to solve complex programming problems involving structured data. Key concepts include row-major memory layout, nested loop processing, and various practical applications like matrix mathematics and data organization.
Part of BCA Programming with C Course (UGCOA22J201)