Multi-Dimensional Arrays in C++
Multi-dimensional arrays are known as arrays of arrays that store similar types of data in tabular form.
Syntax
data_type array_name[size1][size2]....[sizeN];
data_type: Type of data to be stored in the array.
array_name: Name of the array.
size1, size2,…, sizeN: Size of each dimension.
2-dimensional arrays are the most commonly used multi-dimensional arrays in C++.
Example
C++
#include <iostream> using namespace std; int main() { // Declaration and initialization of a 2D array int arr[3][4] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } }; // Accessing elements in the 2D array // Output: 1 cout << "Element at arr[0][0]: " << arr[0][0] << endl; // Output: 7 cout << "Element at arr[1][2]: " << arr[1][2] << endl; // Changing the value of an element // Output: 20 arr[2][3] = 20; cout << "Modified element at arr[2][3]: " << arr[2][3] << endl; // Nested loops for iterating through the 2D array for ( int i = 0; i < 3; i++) { for ( int j = 0; j < 4; j++) { cout << arr[i][j] << " " ; } cout << endl; } return 0; } |
Element at arr[0][0]: 1 Element at arr[1][2]: 7 Modified element at arr[2][3]: 20 1 2 3 4 5 6 7 8 9 10 11 20
C++ Cheatsheet
This is a C++ programming cheat sheet. It is useful for beginners and intermediates looking to learn or revise the concepts of C++ programming. While learning a new language, it feels annoying to switch pages and find different websites for different concepts that are easily understandable. You can learn C++ concepts very easily using this cheat sheet.
C++ is a high-level programming language. It was developed in 1983 by Bjarne Stroustrup at Bell Labs. It is used for developing various applications.
Contact Us