The best way to understand multidimensional arrays is with the simplest possible example.
In this case name for our multidimensional array is multiArr[][]
. We must use two square brackets because our array will have two lines and three elements in each line.
To populate array of this type for every line of elements we have individual curly brackets separated by a comma.
To extract elements, we will use positions.
Position 0 will target the first line. Position 1 will target the second line of elements.
Inside any of these lines with elements we can target individual elements using positions 0, 1, 2 because we have a total of three elements in each line, but in C++ we start counting from position 0.
Run this code:
#include <iostream>
using namespace std;
int main() {
int multiArr[2][3] = {{2, 5, 6}, {4, 7, 9}};
cout << "Elements from First Array: " << endl;
cout << multiArr[0][0] << endl;
cout << multiArr[0][1] << endl;
cout << multiArr[0][2] << endl;
cout << "----------------------------------" << endl;
cout << "Elements from Second Array: " << endl;
cout << multiArr[1][0] << endl;
cout << multiArr[1][1] << endl;
cout << multiArr[1][2] << endl;
return 0;
}
Result:
Elements from First Array:
2
5
6
----------------------------------
Elements from Second Array:
4
7
9
Process returned 0 (0x0) execution time : 0.076 s
Press any key to continue.
No comments:
Post a Comment