Topic 11: Two-Dimensional Arrays

In C++, a two-dimensional array is a collection of variables of the same type arranged in a grid consisting of rows and columns. It can be thought of as an array of arrays.

Declaring and Initializing Two-Dimensional Arrays

To declare a two-dimensional array, specify the type of its elements, followed by the array name and its dimensions in square brackets. Here's an example:

Example: Declaring a Two-Dimensional Array
  • 
    int myArray[3][4];
                                        

You can also initialize a two-dimensional array at the time of declaration:

Example: Initializing a Two-Dimensional Array
  • 
    int myArray[3][4] = {
        {1, 2, 3, 4},
        {5, 6, 7, 8},
        {9, 10, 11, 12}
    };
                                        

Accessing Array Elements

Array elements are accessed using their row and column indices. For example, myArray[0][0] refers to the element in the first row and first column, myArray[1][2] to the element in the second row and third column, and so on.

Example: Accessing Array Elements
  • 
    #include 
    using namespace std;
    
    int main() {
        int myArray[3][4] = {
            {1, 2, 3, 4},
            {5, 6, 7, 8},
            {9, 10, 11, 12}
        };
        cout << "The element at row 1, column 2 is: " << myArray[1][2] << endl;
        cout << "The element at row 0, column 0 is: " << myArray[0][0] << endl;
        return 0;
    }
                                        

Looping Through a Two-Dimensional Array

To process all elements of a two-dimensional array, you can use nested loops. The outer loop iterates through the rows, while the inner loop iterates through the columns:

Example: Looping Through a Two-Dimensional Array
  • 
    #include 
    using namespace std;
    
    int main() {
        int myArray[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) {
                cout << "Element at row " << i << ", column " << j << " is: " << myArray[i][j] << endl;
            }
        }
        return 0;
    }
                                        

Modifying Array Elements

Array elements can be modified by assigning new values to them using their row and column indices:

Example: Modifying Array Elements
  • 
    #include 
    using namespace std;
    
    int main() {
        int myArray[3][4] = {
            {1, 2, 3, 4},
            {5, 6, 7, 8},
            {9, 10, 11, 12}
        };
        myArray[1][2] = 20;  // Changing the element at row 1, column 2 to 20
        cout << "The new value of the element at row 1, column 2 is: " << myArray[1][2] << endl;
        return 0;
    }