In C++, a two-dimensional array is a collection of variables of the same type arranged in a grid consisting of rows and columns. It can be thought of as an array of arrays.
To declare a two-dimensional array, specify the type of its elements, followed by the array name and its dimensions in square brackets. Here's an example:
int myArray[3][4];
You can also initialize a two-dimensional array at the time of declaration:
int myArray[3][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
Array elements are accessed using their row and column indices. For example,
myArray[0][0]
refers to the element in the first row and first column,
myArray[1][2]
to the element in the second row and third column, and so on.
#include
using namespace std;
int main() {
int myArray[3][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
cout << "The element at row 1, column 2 is: " << myArray[1][2] << endl;
cout << "The element at row 0, column 0 is: " << myArray[0][0] << endl;
return 0;
}
To process all elements of a two-dimensional array, you can use nested loops. The outer loop iterates through the rows, while the inner loop iterates through the columns:
#include
using namespace std;
int main() {
int myArray[3][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 4; ++j) {
cout << "Element at row " << i << ", column " << j << " is: " << myArray[i][j] << endl;
}
}
return 0;
}
Array elements can be modified by assigning new values to them using their row and column indices:
#include
using namespace std;
int main() {
int myArray[3][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
myArray[1][2] = 20; // Changing the element at row 1, column 2 to 20
cout << "The new value of the element at row 1, column 2 is: " << myArray[1][2] << endl;
return 0;
}