Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

data structures

2-D arrays in C++

Educative Answers Team

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:

  • 2 is the row index
  • 3 is the column index
  • 5 is the value at this index
svg viewer
indexes of 2-D array


data structures
Copyright ©2022 Educative, Inc. All rights reserved

View all Courses

Keep Exploring