Navigation



6.5 — Multidimensional Arrays

The elements of an array can be of any data type, including arrays! An array of arrays is called a multidimensional array.

int anArray[3][5]; // a 3-element array of 5-element arrays

In this case, since we have 2 subscripts, this is a two-dimensional array. In a two-dimensional array, it is convenient to think of the first subscript as being the row, and the 2nd subscript as being the column. Conceptually, the above two-dimensional array is laid out as follows:

[0][0]  [0][1]  [0][2]  [0][3]  [0][4]
[1][0]  [1][1]  [1][2]  [1][3]  [1][4]
[2][0]  [2][1]  [2][2]  [2][3]  [2][4]

To access the elements of a two-dimensional array, simply use two subscripts:

anArray[2][3] = 7;

To initialize a two-dimensional array, it is easiest to use nested braces, with each set of numbers representing a row:

int anArray[3][5] =
{
{ 1, 2, 3, 4, 5, }, // row 0
{ 6, 7, 8, 9, 10, }, // row 1
{ 11, 12, 13, 14, 15 } // row 2
};

When the C++ compiler processes this list, it actually ignores the inner braces altogether. However, we highly recommend you use them anyway for readability purposes.

Two-dimensional arrays with initializer lists can omit (only) the first size specification:

int anArray[][5] =
{
{ 1, 2, 3, 4, 5, },
{ 6, 7, 8, 9, 10, },
{ 11, 12, 13, 14, 15 }
};

The compiler can do the math to figure out what the array size is. However, the following is not allowed:

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

Because the inner parenthesis are ignored, the compiler can not tell whether you intend to declare a 1×8, 2×4, 4×2, or 8×1 array in this case.

Just like normal arrays, multidimensional arrays can still be initialized to 0 as follows:

int anArray[3][5] = { 0 };

Note that this only works if you explicitly declare the size of the array! Otherwise, you will get a two-dimensional array with 1 row.

Accessing all of the elements of a two-dimensional array requires two loops: one for the row, and one for the column. Since two-dimensional arrays are typically accessed row by row, generally the row index is used as the outer loop.

for (int nRow = 0; nRow < nNumRows; nRow++)
    for (int nCol = 0; nCol < nNumCols; nCol++)
        cout << anArray[nRow][nCol];

Multidimensional arrays may be larger than two dimensions. Here is a declaration of a three-dimensional array:

int anArray[5][4][3];

Three-dimensional arrays are hard to initialize in any kind of intuitive way using initializer lists, so it’s typically better to initialize the array to 0 and explicitly assign values using nested loops.

Let’s take a look at a practical example of a two-dimensional array:

// Declare a 10x10 array
const int nNumRows = 10;
const int nNumCols = 10;
int nProduct[nNumRows ][nNumCols ] = { 0 };

// Calculate a multiplication table
for (int nRow = 0; nRow < nNumRows; nRow++)
    for (int nCol = 0; nCol < nNumCols; nCol++)
        nProduct[nRow][nCol] = nRow * nCol;

// Print the table
for (int nRow = 1; nRow < nNumRows; nRow++)
{
    for (int nCol = 1; nCol < nNumCols; nCol++)
        cout << nProduct[nRow][nCol] << "\t";

    cout << endl;
}

This program calculates and prints a multiplication table for all values between 1 and 9 (inclusive). Note that when printing the table, the for loops start from 1 instead of 0. This is to omit printing the 0 column and 0 row, which would just be a bunch of 0s! Here is the output:

1    2    3    4    5    6    7    8    9
2    4    6    8    10   12   14   16   18
3    6    9    12   15   18   21   24   27
4    8    12   16   20   24   28   32   36
5    10   15   20   25   30   35   40   45
6    12   18   24   30   36   42   48   54
7    14   21   28   35   42   49   56   63
8    16   24   32   40   48   56   64   72
9    18   27   36   45   54   63   72   81
6.6 — C-style strings
Index
6.4 — Sorting an array using selection sort

30 comments to 6.5 — Multidimensional Arrays

  • [...] 6.5 — Multidimensional Arrays  Print This Post This entry is filed under C++ Tutorial. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site. 21 Responses to “6.6 — C-style strings” Comment by sandor 2007-11-12 02:08:15 [...]

  • Rajesh

    Can you just explain how the 2d arrrany multiplications are done?
    and also sorting of string values using array?

  • can u gaVE some example of multidimesional array…thank you

  • Peter LaBanca

    For optimization purposes, so you don’t have to repeat the loops twice creating redundancy, isn’t it better to compact the code from:

    // Calculate a multiplication table
    for (int nRow = 0; nRow < nNumRows; nRow++)
        for (int nCol = 0; nCol < nNumCols; nCol++)
            nProduct[nRow][nCol] = nRow * nCol;  
    
    // Print the table
    for (int nRow = 1; nRow < nNumRows; nRow++)
    {
        for (int nCol = 1; nCol < nNumCols; nCol++)
            cout << nProduct[nRow][nCol] << "t";  
    
        cout << endl;
    }

    to:

    // Calculate a multiplication table
    for (int nRow = 0; nRow < nNumRows; nRow++)
    {
        for (int nCol = 0; nCol < nNumCols; nCol++)
        {
            nProduct[nRow][nCol] = nRow * nCol;
            if(nCol != 0 && nRow != 0)
            {
                cout << nProduct[nRow][nCol] << "t";
            }
        }
        if(nCol != 0 && nRow != 0)
        {
            cout << std::endl;
        }
    }
    

    With processors nowadays I am sure that won’t impact performance that much but every bit counts, especially with bigger, more complex programs.

    Peter LaBanca
    Developer

    • Peter LaBanca

      The “t” is supposed to be escaped. AJAX editor must be interferring.

    • In the real world I would have combined the two loops for efficiency reasons. Here, I did not because I thought it made for a cleaner, easier to follow example.

    • TBM

      Your code wouldn’t compile for me do to nCol falling out of scope in the 2nd if statement. Though this code worked fine for me.

      // Calculate a multiplication table more efficiently
          for (int nRow = 0; nRow < nNumRows; nRow++)
          {
              for (int nCol = 0; nCol < nNumCols; nCol++)
              {
                  nProduct[nRow][nCol] = nRow * nCol;
                  if(nCol != 0 && nRow != 0)
                      cout << nProduct[nRow][nCol] << "\t";
              }
              if(nRow != 0)
              cout << endl;
          }
      
  • Chiamaka

    in what section did you talk about “const”?

  • FuturePixstar

    i belive it’s 2.8

  • detroit

    is there any body to create a multiplication table using array in c++?

  • Kevin

    g++ compiler required double { { } } braces as follows compared to the single in the example

    int nProduct[nNumRows ][nNumCols ] = { {0} };
    • ca336458

      g++ didn’t require it for me as an error, just gave me a warning when using just the one set of braces. That warning went away when I used 2: int nProduct[nNumRows ][nNumCols ] = {{ 0 }};

  • You may also remove the if statement to shorten the code.

    // Calculate a multiplication table more efficiently
        for (int nRow = 0; nRow < nNumRows; nRow++)
        {
            for (int nCol = 0; nCol < nNumCols; nCol++)
            {
                nProduct[nRow][nCol] = nRow * nCol;
                if(nCol != 0 && nRow != 0)
                    cout << nProduct[nRow][nCol] << "\t";
            }
            if(nRow != 0)
            cout << endl;
        }
    
  • Cheesefriend
    using a 2 dimensional array that is printed to the screen
    is properly the eaisest way to make a 2d game map you
    can move around on for those that is intrested in that.
    
    made a game like that in matlab:)
    
  • in multidimensional array ,
    one column contain a integer,
    another column contain a string,
    how we declare an array to accept a value

  • I will give two kinds of methods (one is similar to the author’s, but a bit shorter)

    #include <iostream>
    #include <iomanip>
    using namespace std;
    //
    // int main()
    // {
    // 	int row = 10;
    // 	int column = 10;
    // 	int table_array[row][column];
    //
    // 	for (int i = 1; i < row; i++)
    // 	{
    // 		for (int j = 1; j < column; j++)
    // 		{
    // 			table_array[i][j] = i*j;
    // 			cout << setw(5) << table_array[i][j];
    // 		}
    // 		cout << endl;
    // 	}
    // 	return 0;
    //
    //
    // }
    
    // int main()
    // {
    // 	int row = 13;
    // 	int column = 13;
    // 	int table_array[row][column];
    //
    // 	for (int i = 1; i < row; i++)
    // 	{
    // 		int temp = 0;
    // 		for (int j = 1; j < column; j++)
    // 		{
    //
    // 			temp += i;
    // 			table_array[i][j] = temp;
    // 			cout << setw(4) << table_array[i][j];
    // 		}
    // 		cout << endl;
    // 	}
    // 	return 0;
    // }
    

    The first method just takes the cout into the loop as well.
    The second is just the stupid-way to do this problem, using additional instead.

  • DaMonroe

    Great, but if you don’t know the length of the actual number of rows, the outer loop can’t be a “for” loop. How could a “while” be controlled when filling an array from a file?

    • copier1

      Arrays have to be initialized with the dimension size. In a later lesson you learn how to do this at run time instead of at the time it’s compiled. In either case, the size does have to be dimensions do have to be known beforehand.

      You can use a function or a class to determine the length and number of rows from the file.

  • Adi_ida

    How to convert an array of 2 dimensions to one dimension?

  • Hi Alex..I am a begginer in C++. I have written a code to add matrices,the code is all fine the only problem is that when i m printing the output it is looking something like this 12 12 12 12 12 instead of this i want it as 12 12 12
    12 12 12
    12 12 12..Can u please help me…

  • i.e in matrix form i want to print the output…please help me out…

  • ProgrammerJupiter

    anArray[2][3] = 7;

    int anArray[3][5] =
    {
    { 1, 2, 3, 4, 5, }, // row 0
    { 6, 7, 8, 9, 10, }, // row 1
    { 11, 12, 13, 14, 15 } // row 2
    };

    Just curious wouldnt anArray[2][3] = 14? if i am understanding how this works properly

  • warren2c

    Hi guys.

    Im a beginner and have a project similar to the one described above. For the above project, how do you put all the for loop part into a function? Say if you had multiple arrays of different values, but all of the same size?

  • ErinDwight

    Please help… I have a migraine from trying to do this homework. Could you please help?

    Write a C++ program that finds and displays the maximum value
    in a two-dimensional array of integers. The array should be declared as a 4-by-5 array of
    integers and initialized with the data 16, 22, 99, 4, 18, -258, 4, 101, 5, 98, 105, 6, 15, 2,
    45, 33, 88, 72, 16, and 3.

    #include
    #include
    #include

    using namespace std;

    int main(int argc, char *argv[])
    {
    int array [] = {16, 22, 99, 4, 18, -258, 4, 101, 5, 98, 105, 6, 15, 2, 45, 33, 88, 72, 16, 3};
    {
    for(int j = 0; j < array[i].length; j++)
    {
    if(max < array[i][j])
    {
    max = array[i][j];
    }
    }
    }

    system("PAUSE");
    return EXIT_SUCCESS;
    }

    • billy1014

      I saw this and used this as practice. Here’s the solution in case anyone wants it. Let me know if you find a better way.

      int search()
      {

      int array [4][5] = {16, 22, 99, 4, 18, -258, 4, 101, 5, 98, 105, 6, 15, 2, 45, 33, 88, 72, 16, 3};

      int xo = 0;
      int xi = 0;
      for(int nRow = 0; nRow < 4; nRow++)
      {
      for(int nCol = 0; nCol xo)
      {xo = xi;}
      }
      }
      return xo;
      }

You must be logged in to post a comment.