C++

How to work with multidimensional arrays in C++

Until now the arrays we discussed are one-dimensional arrays. C++ also supports storing data in multiple dimensions. A two-dimensional array can represent tabular data i.e., in rows and columns. Syntax for declaring a two-dimensional array is as follows:

type  array-name[rows][coulumns];




We can initialize a two-dimensional array at the time of declaration itself as shown below:

int  data[3][3] = {{1,2,3},{4,5,6},{7,8,9}};

In the above statement, data is a two-dimensional array having three rows and three columns. We can imagine a two-dimensional array as an array of arrays. Consider the following program which demonstrates reading and displaying elements in a two-dimensional array:

Input and output for the above program is as follows:

Observe how nested for loops are used to read and print the array elements effectively.

Dynamic Arrays

Consider you are writing a program to store student records which are bound to increase over time. There is now way to assume the size of the array before hand. In such cases static arrays are a bad choice. Instead, use dynamic arrays.

Dynamic arrays can be created in C++ programs using vector class which is available in the header file vector. Since vector uses template syntax and they are not at discussed, let’s look at a program which demonstrates creating and using a vector:

Input and output for the above program is as follows:

In the above program, size() function returns the size of the vector (array) and push_back() function inserts the given element at the end of the vector (array).

Take your time to comment on this article.

Leave a Comment