Two Dimensional Array in C++
In C++, a two-dimensional array is a grouping of elements arranged in rows and columns. Each element is accessed using two indices: one for the row and one for the column, which makes it easy to visualize as a table or grid.
Syntax of 2D array
data_Type array_name[n][m];
Where,
- n: Number of rows.
- m: Number of columns.
Example: The C++ Program to Illustrate the Two-Dimensional Array
// c++ program to illustrate the two dimensional array
#include <iostream>
using namespace std;
int main()
{
// Declaring 2D array
int arr[4][4];
// Initialize 2D array using loop
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
arr[i][j] = i + j;
}
}
// Printing the element of 2D array
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
cout << arr[i][j] << " ";
}
cout << endl;
}
return 0;
}
Output
0 1 2 3 1 2 3 4 2 3 4 5 3 4 5 6
Explanation
In the above code we have declared a 2D array with 4 rows and 4 columns after that we initialized the array with the value of (i+j) in every iteration of the loop. Then we are printing the 2D array using a nested loop and we can see in the below output that there are 4 rows and 4 columns.
C++ Arrays
In C++, an array is a data structure that is used to store multiple values of similar data types in a contiguous memory location.
For example, if we have to store the marks of 4 or 5 students then we can easily store them by creating 5 different variables but what if we want to store marks of 100 students or say 500 students then it becomes very challenging to create that numbers of variable and manage them. Now, arrays come into the picture that can do it easily by just creating an array of the required size.