Multi-Dimensional Arrays
As we remember, an array is a set of variables that allows you to store several values of the same type. A multi-dimensional array is an array of arrays. To declare such an array, specify the type of variables it contains and the name of the array, followed by the square brackets where we indicate how many elements each of the main and subarrays have.
For example:
int a[3][4];
Here we declared a two-dimensional 3x4 integer array a. It means that the array has 3 elements, and each of them is an array with 4 elements. Letβs visualize the array as the table:
Remember that indexing in arrays starts from 0.
As with ordinary arrays, multi-dimensional arrays may be declared by specifying each element in curly braces separated by a comma:
char letters[3][2] {
{'a', 'b'}, // 1st row
{'c', 'd'}, // 2nd row
{'e', 'f'} // 3rd row
};
We can get access to the element of the 2-dimensional array by specifying the name of the array with its row and column indexes:
cout << letters[2][0]; // index 2 means 3rd row, index 0 means 1st column
Each pair of square brackets in an array declaration adds another dimension. You can create arrays of any dimension you want. Further in this course, we will only work with two-dimensional arrays.
Thanks for your feedback!
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat
Ask me questions about this topic
Summarize this chapter
Show real-world examples
Awesome!
Completion rate improved to 2.94
Multi-Dimensional Arrays
Swipe to show menu
As we remember, an array is a set of variables that allows you to store several values of the same type. A multi-dimensional array is an array of arrays. To declare such an array, specify the type of variables it contains and the name of the array, followed by the square brackets where we indicate how many elements each of the main and subarrays have.
For example:
int a[3][4];
Here we declared a two-dimensional 3x4 integer array a. It means that the array has 3 elements, and each of them is an array with 4 elements. Letβs visualize the array as the table:
Remember that indexing in arrays starts from 0.
As with ordinary arrays, multi-dimensional arrays may be declared by specifying each element in curly braces separated by a comma:
char letters[3][2] {
{'a', 'b'}, // 1st row
{'c', 'd'}, // 2nd row
{'e', 'f'} // 3rd row
};
We can get access to the element of the 2-dimensional array by specifying the name of the array with its row and column indexes:
cout << letters[2][0]; // index 2 means 3rd row, index 0 means 1st column
Each pair of square brackets in an array declaration adds another dimension. You can create arrays of any dimension you want. Further in this course, we will only work with two-dimensional arrays.
Thanks for your feedback!