Get up to 80 % extra points for free! More info:

Lesson 11 - Multidimensional arrays in C++

In the previous exercise, Solved tasks for C++ lessons 9-10, we've practiced our knowledge from previous lessons.

Lesson highlights

Are you looking for a quick reference on multidimensional arrays in C++ instead of a thorough-full lesson? Here it is:

Shortened initialization of a 2D array:

int cinema[5][5] = {
    { 0, 0, 0, 0, 1 },
    { 0, 0, 0, 1, 1 },
    { 0, 0, 1, 1, 1 },
    { 0, 0, 0, 1, 1 },
    { 0, 0, 0, 0, 1 }
};

Writing 1 at the position [1][0]:

cinema[1][0] = 1;

Reading the value (now 1) at the position [1][0]:

cout << cinema[1][0] << endl;

Printing the whole 2D array:

for (int j = 0; j < 5; j++)
{
    for (int i = 0; i < 5; i++)
    {
        cout << cinema[j][i];
    }
    cout << endl;
}

Declaring an empty 2D array of a given size:

int cinema[5][5];

Would you like to learn more? A complete lesson on this topic follows.

We've already worked with one-dimensional arrays which we can imagine as a row of boxes in computer memory.

Array structure in C++ - C++ Basic Constructs

(An array of eight numbers can be seen in the image)

Although it's not too common, you may sometimes encounter multidimensional arrays. Especially, when it comes to game applications or simulations in general. In math, they're useful for representing matrices.

Two-dimensional array

A good representation of a 2-dimensional array is a grid because, technically, it is one. A practical application for 2-dimensional arrays would be to use them to store the available seats in a cinema. Here's a visual representation of what I'm referring to:

The 2d array structure in C++ - C++ Basic Constructs

(We can see the available seats of the cinema in the picture )

Of course, the cinema would be bigger in real life, but this array is just fine as an example. 0 means the seat is available, 1 means that isn't. Later, we could also add 2 for reserved seats and so on. It would be more appropriate to create some constants for these states, but we'll get into that later. For now, we'll work with numbers.

In C++, we declare the 2D array like this:

int cinema[5][5];
// Filling with zeroes
for (int j = 0; j < 5; j++)
    for (int i = 0; i < 5; i++)
        cinema[j][i] = 0;

We have to keep in mind to initialize the array with zeroes since we can't be sure which values are currently in there in C++. Another thing to think about (and write down as a comment ideally) is the order of the coordinates. In our case, the first number will index columns and the second rows.

Filling the data

Let's fill the cinema room with 1s now as you can see in the picture above. Since we'll be lazy as good programmers should be, we'll use for loops to create a row of 1s :) To access an item of the 2D array we have to enter two coordinates.

cinema[2][2] = 1; // center
for (int i = 1; i < 4; i++) // fourth row
{
    cinema[i][3] = 1;
}
for (int i = 0; i < 5; i++) // the last row
{
    cinema[i][4] = 1;
}

The output

We'll print the array using a loop as we did before. We'll need 2 loops for the 2d array, the first one will iterate over columns and the second one over rows). We'll nest the loops in so that the outer loop iterates over the rows and the inner one iterates over the columns of the current row. Once a row has been printed, we'll have to break a line. Each loop must have a different control variable:

for (int j = 0; j < 5; j++)
{
    for (int i = 0; i < 5; i++)
    {
        cout << cinema[i][j];
    }
    cout << endl;
}

The result:

Console application
00000
00000
00100
01110
11111

N-dimensional arrays

Sometimes, it may be useful to create an array of even more dimensions. We can all at least imagine a 3D array. Adding to the cinema analogy, we'll say ours has multiple floors, or more rooms. The visualization could then look like this:

The 3D array structure in C++ - C++ Basic Constructs

We can create the 3D array the same way we created the 2D array:

int cinemas[5][5][3];

The code above creates the 3D array you saw in the picture. We can access it through the indexer, i.e. square brackets, as before. However, now we have to enter 3 coordinates.

cinemas[3][2][1] = 1; // the cinema's second floor, third row, fourth seat

Shortened initialization of multidimensional arrays

I'll also mention that even multidimensional arrays can be initialized with values directly (this code creates and initializes a crowded cinema room as you can see in the picture):

int cinema[5][5] = {
    { 0, 0, 0, 0, 1 },
    { 0, 0, 0, 1, 1 },
    { 0, 0, 1, 1, 1 },
    { 0, 0, 0, 1, 1 },
    { 0, 0, 0, 0, 1 }
};

(The array in this code is rotated since we define columns which are declared as rows here).

Jagged arrays

We've only talked about rectangular arrays up until now. The C++ language doesn't allow us to create an array of different lengths within its inner arrays in each dimension (statically). However, theoretically, it would look like this:

Jagged arrays in the C++ programming language - C++ Basic Constructs

Of course, we are able to create arrays like these, but we'd have to remember the number of items in each dimension since C++ doesn't remember that. We'd also have to allocate memory dynamically, so we'll put this topic off to the side until we get to the advanced C++ programming courses.

In conclusion, I would like to add that some people who can't use objects properly use 2D arrays to store multiple sets of data for a single entity. For example, imagine that we need to store the length, width, and height of five cell phones. Although you may think that a 3D array would be best for the situation, it can be pulled off with an ordinary 1D array (specifically a list of objects or structures of the Phone type). We'll get to structures at the end if this course and we'll go over objects in the object-oriented programming course. If you feel like you could still use some more practice, go ahead and give the exercises for this lesson a shot.

In the next lesson, Mathematical functions in C++ - The cmath library, we'll look at basic math functions and finish the basic constructs course.


 

Did you have a problem with anything? Download the sample application below and compare it with your project, you will find the error easily.

Download

By downloading the following file, you agree to the license terms

Downloaded 3x (490.04 kB)
Application includes source codes in language C++

 

Previous article
Solved tasks for C++ lessons 9-10
All articles in this section
C++ Basic Constructs
Skip article
(not recommended)
Mathematical functions in C++ - The cmath library
Article has been written for you by David Capka Hartinger
Avatar
User rating:
No one has rated this quite yet, be the first one!
The author is a programmer, who likes web technologies and being the lead/chief article writer at ICT.social. He shares his knowledge with the community and is always looking to improve. He believes that anyone can do what they set their mind to.
Unicorn university David learned IT at the Unicorn University - a prestigious college providing education on IT and economics.
Activities