Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

arrays
data structures

2-D arrays in C++

Educative Answers Team

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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
svg viewer
indexes of 2-D array

RELATED TAGS

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

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring