How to create and use a 2D array in C++

In C++, you can use two-dimensional arrays to organize data in a table-like manner. In mathematics, especially in linear algebra, 2D arrays provide an optimal structure for representing matrices.

What is a 2D array in C++?

In C++, a 2D array is a data structure that arranges elements in a two-dimensional, table-like format. Unlike one-dimensional arrays, which simply store elements in a sequence, a 2D array organizes data into rows and columns. Each element in a 2D array is identified by its row and column indices, facilitating easy access and manipulation of individual data points. From mathematical operations involving matrices to handling raster data, there are various uses for this type of array.

How is a 2D array structured in C++?

In C++, the syntax for declaring 2D arrays consists of the following elements:

data_type arrayName[num_rows][num_cols];
c++
  • data_type: The data type specifies the type of data that should be stored in the 2D array. This can be, for example, int for integers, double for floating point numbers or user-defined data types.
  • arrayName: The name acts as an identifier that you can use to access the entire array.
  • num_rows: This part of the syntax specifies how many rows the 2D array should have.
  • num_cols: Here you specify the number of columns for each row in the 2D array.

In the example below, we are going to define a 2D array called matrix. It consists of 3 rows and 4 columns and has a total of 12 elements.

int matrix[3][4] = {{1, 2, 3, 4},
    {5, 6, 7, 8},
    {9, 10, 11, 12}};
c++

How to output a 2D array in C++

You can output a 2D array using a for loop. The outer loop iterates over the rows, while the inner loop iterates over the columns of each row. The statement std::cout << matrix[i][j] << " "; displays each element. After each row, we are going to create a new row using std::cout << std::endl;. This ensures a better format for the output.

#include <iostream>
int main() {
    int matrix[3][4] = {{1, 2, 3, 4},
                        {5, 6, 7, 8},
                        {9, 10, 11, 12}};
    for (int i = 0; i < 3; ++i) {
        for (int j = 0; j < 4; ++j) {
            std::cout << matrix[i][j] << " ";
        }
 
        std::cout << std::endl;
    }
    return 0;
}
c++

The elements of the 2D array are displayed line by line in the output:

1 2 3 4
5 6 7 8
9 10 11 12
c++

Examples of how to use two-dimensional arrays in C++

Programming with C++ means you’ll be working with arrays sooner or later. In the following section, we’ll show you typical applications for 2D arrays in C++.

2D arrays with user input

Here’s a straightforward C++ example where we let the user define a 2D array dynamically. First, we ask the user to input the number of rows and columns, followed by the elements for the array.

#include <iostream>
int main() {
    int numRows, numCols;
    std::cout << "Number of rows: ";
    std::cin >> numRows;
    std::cout << "Number of columns: ";
    std::cin >> numCols;
    int userArray[numRows][numCols];
    std::cout << "Please enter in elements:\n";
    for (int i = 0; i < numRows; ++i) {
        for (int j = 0; j < numCols; ++j) {
            std::cout << "Element [" << i << "][" << j << "]: ";
            std::cin >> userArray[i][j];
        }
    }
    std::cout << "2D array:\n";
    for (int i = 0; i < numRows; ++i) {
        for (int j = 0; j < numCols; ++j) {
            std::cout << userArray[i][j] << " ";
        }
        std::cout << std::endl;
    }
    return 0;
}
c++

If 2 rows and 3 columns and the values 1, 2, 3, 4, 5, 6 are passed as user input, the 2D array will be:

2D array:
1 2 3
4 5 6
c++

Adding matrices with 2D arrays

With C operators such as +, we can easily add matrices in C++ using 2D arrays.

#include <iostream>
const int numRows = 2; 
const int numCols = 2; 
void matrixAddition(int A[][numCols], int B[][numCols], int result[][numCols]) {
    for (int i = 0; i < numRows; ++i) {
        for (int j = 0; j < numCols; ++j) {
            result[i][j] = A[i][j] + B[i][j];
        }
    }
}
void displayMatrix(int matrix[][numCols]) {
    for (int i = 0; i < numRows; ++i) {
        for (int j = 0; j < numCols; ++j) {
            std::cout << matrix[i][j] << " ";
        }
        std::cout << std::endl;
    }
}
int main() {
    int matrixA[numRows][numCols] = {{1, 2}, {3, 4}};
    int matrixB[numRows][numCols] = {{5, 6}, {7, 8}};
    int resultMatrix[numRows][numCols];
    matrixAddition(matrixA, matrixB, resultMatrix);
    // Output of matrix A and B and their sum
    std::cout << "Matrix A:\n";
    displayMatrix(matrixA);
    std::cout << "\nMatrix B:\n";
    displayMatrix(matrixB);
    std::cout << "\nSum (A + B):\n";
    displayMatrix(resultMatrix);
    return 0;
}
c++

First, we create two 2x2 matrices, A and B. Then, we calculate their sum, which will be displayed in the resulting matrix. The matrixAddition function accepts the two initial matrices and the resulting matrix as parameters and performs the addition. The displayMatrix function then displays the sum of matrices A and B on the console.

Here’s the output:

Matrix A:
1 2
3 4
Matrix B:
5 6
7 8
Sum (A + B):
6 8
10 12
c++
Web Hosting
Fast, scalable hosting for any website
  • 99.9% uptime
  • PHP 8.3 with JIT compiler
  • SSL, DDoS protection, and backups
Was this article helpful?
We use cookies on our website to provide you with the best possible user experience. By continuing to use our website or services, you agree to their use. More Information.
Page top