C++ Two-Dimensional Arrays
A two-dimensional array in C++ is an array of arrays. It is commonly used to represent tables or matrices with rows and columns.
1. Array Declaration
A two-dimensional array is declared by specifying rows and columns.
data_type array_name[rows][columns];
// Example
int matrix[3][4];
2. Array Initialization
Two-dimensional arrays can be initialized at the time of declaration.
int matrix[2][3] = {
{1, 2, 3},
{4, 5, 6}
};
3. Accessing Elements
Elements are accessed using two indices: one for row and one for column. Indexing starts from 0.
#include <iostream>
using namespace std;
int main() {
int matrix[2][3] = {{1,2,3},{4,5,6}};
cout << "Element at row 1, column 2: " << matrix[1][2] << endl;
return 0;
}
4. Looping Through a 2D Array
Nested loops are used to access all elements of a two-dimensional array.
#include <iostream>
using namespace std;
int main() {
int matrix[2][3] = {{1,2,3},{4,5,6}};
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
cout << matrix[i][j] << " ";
}
cout << endl;
}
return 0;
}
5. Matrix Addition Example
Two-dimensional arrays are commonly used for matrix operations such as addition.
#include <iostream>
using namespace std;
int main() {
int a[2][2] = {{1,2},{3,4}};
int b[2][2] = {{5,6},{7,8}};
int sum[2][2];
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
sum[i][j] = a[i][j] + b[i][j];
}
}
cout << "Result Matrix:\n";
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
cout << sum[i][j] << " ";
}
cout << endl;
}
return 0;
}
6. Common Mistakes
1. Accessing elements outside the row or column limits. 2. Confusing row and column indices. 3. Forgetting to use nested loops for full traversal.
Conclusion
C++ two-dimensional arrays are useful for representing matrices and tables. Proper understanding of declaration, indexing, and nested loops is essential for working with 2D arrays effectively.
Codecrown