Trusted answers to developer questions

2-D arrays in C++

Free System Design Interview Course

Many candidates are rejected or down-leveled due to poor performance in their System Design Interview. Stand out in System Design Interviews and get hired in 2024 with this popular free course.

Similar to a 1-D array, a 2-D array is a collection of data cells. 2-D arrays work in the same way as 1-D arrays in most ways; however, unlike 1-D arrays, they allow you to specify both a column index and a row index.

All the data in a 2D array is of the same type.

svg viewer

Declaring 2-D arrays in C++

Similar to the 1-D array, we must specify the data type, the name, and the size of the array. The size of a 2-D array is declared by the number of rows and number of columns. For example:

#include <iostream>
using namespace std;
int main() {
const int number_of_rows=5;
const int number_of_columns=4;
// declaring a 2-D array with 5 rows and 4 columns
int arr[number_of_rows][number_of_columns];
}

In the example above, arr is the name of the array.

The total number elements in this 2-D array is:

number_of_rows * number_of_columns

So the total number elements in arr is 20.

Accessing 2-D arrays in C++

Like 1-D arrays, you can access individual cells in a 2-D array by using subscripts that specify the indexes of the cell you want to access. However, you now have to specify two indexes instead of one. The expression looks like this:

arr[2][3]=5;
  • 2 is the row index
  • 3 is the column index
  • 5 is the value at this index
indexes of 2-D array
indexes of 2-D array

RELATED TAGS

arrays
data structures
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?