C++ Multidimensional Arrays

In C++, a multidimensional array is an array of arrays. It is a data structure that can store values of the same data type in a tabular form with rows and columns. The simplest example of a two-dimensional array is a matrix.

To declare a multidimensional array in C++, you need to specify the number of rows and columns. The syntax for declaring a two-dimensional array is as follows.

data_type array_name [row_size][col_size];

Here, data_type represents the data type of the elements in the array, array_name represents the name of the array, row_size represents the number of rows in the array, and col_size represents the number of columns in the array.

For example, to declare a two-dimensional integer array with three rows and four columns, you can use the following code:

int matrix[3][4];

You can also initialize the array at the time of declaration by providing the initial values. The syntax for initializing a two-dimensional array is as follows:

data_type array_name[row_size][col_size] = {{val1, val2, val3, ...}, {val1, val2, val3, ...}, ...};

Here, val1, val2, val3, etc., represent the initial values for the array elements.

For example, to initialize a two-dimensional integer array with three rows and four columns, you can use the following code:

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

To access an element in a multidimensional array, you need to specify the row and column index. The syntax for accessing an element in a two-dimensional array is as follows:

array_name[row_index][col_index]

For example, to access the element at row 1 and column 2 in the above array, you can use the following code:

int element = matrix[1][2]; // element = 7

Here’s a complete example program that demonstrates how to work with a two-dimensional array in C++:

#include <iostream>

using namespace std;

int main() {
    int matrix[3][4] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};
    
    // print the matrix
    for(int i = 0; i < 3; i++) {
        for(int j = 0; j < 4; j++) {
            cout << matrix[i][j] << " ";
        }
        cout << endl;
    }
    
    // change an element in the matrix
    matrix[1][2] = 100;
    
    // print the modified matrix
    for(int i = 0; i < 3; i++) {
        for(int j = 0; j < 4; j++) {
            cout << matrix[i][j] << " ";
        }
        cout << endl;
    }
    
    return 0;
}

In this program, we first declare and initialize a two-dimensional integer array named matrix. We then use two nested loops to print the matrix. After that, we modify an element in the matrix by assigning a new value to it. Finally, we print the modified matrix.

Wordpress Social Share Plugin powered by Ultimatelysocial
Wordpress Social Share Plugin powered by Ultimatelysocial