โ Two-Dimensional Arrays (2D Arrays)
โ 1. Definition of Two-Dimensional Array
A Two-Dimensional Array (2D Array) is a collection of elements of the same data type stored in the form of a table (rows and columns).
โ It is also called a Matrix Array.
๐ Example:
It looks like a grid:
Row\Col 0 1 2
0 10 20 30
1 40 50 60
2 70 80 90
โ 2. Declaration of 2D Array
โ Syntax (C Language)
datatype array_name[rows][columns];
โ Example:
int A[3][3];
This means:
- 3 rows
- 3 columns
- Total elements = 3 ร 3 = 9
โ 3. Initialization of 2D Array
โ Example:
int A[2][3] = {
{10, 20, 30},
{40, 50, 60}
};
Another way:
int A[2][3] = {10,20,30,40,50,60};
โ 4. Accessing Elements in 2D Array
Elements are accessed using two indexes:
โ Format:
A[i][j]
Where:
i= row numberj= column number
โ Example:
A[0][0] = 10A[1][2] = 60
โ 5. Memory Representation of 2D Array
A 2D array is stored in contiguous memory, but the elements are stored row-wise in C.
โ (A) Row Major Order (Used in C / C++)
In Row Major Order, all elements of first row are stored first, then second row, and so on.
โ Example:
A[0][0] A[0][1] A[0][2] A[1][0] A[1][1] A[1][2]
โ Address Calculation Formula (Row Major)
[
LOC(A[i][j]) = Base(A) + [(i \times N) + j] \times W
]
Where:
- Base(A) = Base address of array
- N = Number of columns
- W = Size of each element
- i = row index
- j = column index
โ 6. Traversing a 2D Array
To traverse a 2D array, we use nested loops.
โ Example Program (Traversal):
for(i=0; i<rows; i++)
{
for(j=0; j<cols; j++)
{
printf("%d ", A[i][j]);
}
printf("\n");
}
โ 7. Operations on 2D Arrays
โ 1. Insertion
In 2D arrays, insertion means assigning a value to any cell:
โ Example:
A[1][1] = 99;
โ 2. Deletion
Deletion is not direct like linked list. We can:
- Replace value by
0or-1 - Shift elements (complex)
โ Example:
A[1][1] = 0;
โ 3. Searching
Search an element by scanning all values:
โ Example:
for(i=0;i<rows;i++)
{
for(j=0;j<cols;j++)
{
if(A[i][j] == key)
{
//found
}
}
}
Time Complexity: โ O(rows ร cols)
โ 8. Applications of 2D Arrays
2D arrays are used in many real-life and programming problems:
โ Applications:
- Matrix representation
- Student marks table
- Image processing (pixels)
- Games (chess board, tic-tac-toe)
- Graph representation (Adjacency Matrix)
โ 9. Advantages of 2D Arrays
โ Benefits:
- Easy representation of matrix data
- Fast access using index
- Easy to use with loops
- Suitable for tables and grids
โ 10. Disadvantages of 2D Arrays
โ Limitations:
- Fixed size (static memory)
- Memory wastage if not fully used
- Insertion and deletion are difficult
- Requires contiguous memory allocation
โ Conclusion
A two-dimensional array stores data in row and column form like a table. It is very useful for representing matrix data such as marks, images, and graphs. In C language, 2D arrays are stored in row-major order, and elements are accessed using two indexes A[i][j].
