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

Lesson 10 - Multidimensional arrays in the C language

In the previous exercise, Solved tasks for C lessons 8-9, 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]:

printf("%d", cinema[1][0]);

Printing the whole 2D array:

int i, j;
for (j = 0; j < 5; j++)
{
    for (i = 0; i < 5; i++)
    {
        printf("%d", cinema[j][i]);
    }
    printf("\n");
}

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.

Until now, we've only worked with single-dimensional arrays in the C language. We can imagine a single-dimensional array as a row of boxes in computer memory.

Array structure in the C language - The C Language 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. They can be used for things like representing a game area or matrices in mathematics.

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 the C language - The C Language Basic Constructs

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

Of course, a cinema would be bigger in real life, but this array is just fine as an example. 0 means the seat is available, whereas, 1 means that isn't. Later on, 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 the C programming language, we declare 2D arrays like this:

int cinema[5][5];
int i, j;
// filling with zeros
for (j = 0; j < 5; j++)
    for (i = 0; i < 5; i++)
        cinema[j][i] = 0;

We have to remember to initialize the array with zeros first since we can be never sure which values are in a new array in the C language. It's also important to think about (and ideally to write down as a comment) what is the order of the coordinates. In our case, the first number will index the column and the second one will index the row.

Modification

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

cinema[2, 2] = 1; // center
for (i = 1; i < 4; i++) // fourth row
{
    cinema[i][3] = 1;
}
for (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 order so the outer loop can iterate over the rows and the inner one over the columns of the current row. After printing a row, we must break a line. Each loop must have a different control variable:

for (j = 0; j < 5; j++)
{
    for (i = 0; i < 5; i++)
    {
        printf("%d", cinema[i][j]);
    }
    printf("\n");
}

The result:

Console application
00000
00000
00100
01110
11111

Nth-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 generally more rooms. The visualization could then look like this:

The 3D array structure in the C language - The C Language Basic Constructs

We are able to create a 3D array the same way we created the 2D array:

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

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

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

Shortened initialization of multidimensional arrays

I'll also mention that even multidimensional arrays can be initialized with values directly (the following 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 mainly talked about rectangular arrays until now. The C language doesn't allow us to create an array of different lengths of inner arrays in each dimension statically. However, it would look like this:

Jagged arrays in the C programming language - The C Language Basic Constructs

Of course, we're able to create even arrays like these, but we have to remember the number of items in each dimension since C doesn't remember that. It's also necessary to allocate memory dynamically. Therefore, we'll leave this topic 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 of a single entity. For example, imagine that we want 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 of the PHONE type). We'll go over all of that 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 the C language - The Math library, we'll look at basic math functions and the math.h library.


 

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 7x (142.74 kB)
Application includes source codes in language C

 

Previous article
Solved tasks for C lessons 8-9
All articles in this section
The C Language Basic Constructs
Skip article
(not recommended)
Mathematical functions in the C language - The Math 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