Two Dimensional Array

Estimated reading: 7 minutes 125 Views

A two-dimensional array in C++ is a structure that allows you to store elements in a tabular form, organized in rows and columns. It is essentially an array of arrays.

Here’s an explanation of a two-dimensional array in C++:

  • Declaration and Initialization:
// Declaration of a 2D array
int matrix[3][4];

// Initialization of a 2D array
int anotherMatrix[2][3] = { {1, 2, 3}, {4, 5, 6} };
  • Structure:

In a 2D array, elements are arranged in rows and columns. The first index represents the row, and the second index represents the column.

  • Memory Representation:

In memory, a 2D array is stored in a contiguous block of memory. The elements of each row are stored together, and rows are stored one after the other.

  • Accessing Elements:
int value = matrix[1][2];  // Accessing the element in the second row and third column
  • Initialization with Nested Loops:

Common Operations:

– Iterating through elements using nested loops.
– Performing operations on each element.
– Passing a 2D array to functions.

Example 1:

#include <iostream>
using namespace std;
int main()
{
    int a[3][4];
    for (size_t i = 0; i < 3; i++)
    {
        for (size_t j = 0; j < 4; j++)
        {
            cin >> a[i][j];
        }
    }
    for (size_t r = 0; r < 3; r++)
    {
        for (size_t c = 0; c < 4; c++)
        {
            cout << a[r][c] << " ";
        }
        cout << endl;
    }
    return 0;
}

This code allows the user to input values into a 2D array a[3][4] and then prints the array in a tabular form.

Here are the key points:

  1. 2D Array Input:
    The nested loops (for loops) are used to iterate over each element of the 2D array and input values using cin.
  2. 2D Array Output:
    Another set of nested loops is used to iterate over each element of the 2D array and output the values using cout.
    The inner loop prints each row, and the outer loop moves to the next row, creating a tabular form.
  3. Tabular Output:
    The cout << a[r][c] << ” “; statement prints each element of the 2D array followed by a space.
    The cout << endl; statement is used to move to the next line after printing each row.
  4. User Interaction:
    The user is prompted to input values for each element of the 2D array. The input is expected to be provided in a row-wise fashion.
  5. Array Size:
    The array a is declared with 3 rows and 4 columns, creating a 3×4 matrix.

This code allows the user to interactively input values into a 3×4 2D array and then displays the array in a tabular format.

Example 2:

#include <iostream>
using namespace std;

int main() {
    // Initialization of a 2D array with predefined values
    int arr[2][4] = {{1, 1, 1, 1}, {2, 2, 2, 2}};
    
    // Variable to store the sum of array elements
    int sum = 0;

    // Nested loops to iterate over each element of the 2D array
    for (size_t r = 0; r < 2; r++) {
        for (size_t c = 0; c < 4; c++) {
            // Accumulate the values to calculate the sum
            sum += arr[r][c];
        }
    }

    // Output the sum of array elements
    cout << "sum = " << sum << endl;

    return 0;
}

Output:

In this specific example, the sum is calculated as follows: 1 + 1 + 1 + 1 + 2 + 2 + 2 + 2 = 12.
The output will be sum = 12.

This code is a simple illustration of how to iterate over elements in a 2D array and perform a basic operation, in this case, calculating the sum of all elements.

Example 3:

#include <iostream>
using namespace std;
int main()
{
    int marks[10][5];
    for (size_t r = 0; r < 10; r++)
    {
        for (size_t c = 0; c < 5; c++)
        {
            cout << "Enter mark " << c + 1 << " " << "for student " << r + 1 << ": " << endl;
            cin >> marks[r][c];
        }
    }
    double s = 0;
    float avg[10];
    for (size_t r = 0; r < 10; r++)
    {
        s = 0;
        for (size_t c = 0; c < 5; c++)
        {
            s += marks[r][c];
        }
        avg[r] = s / 5;
        cout << "Average for student #" << r + 1 << " = "<< avg[r] << endl;
    }
    return 0;
}

This code collects marks for 10 students in 5 subjects, calculates the average mark for each student, and then outputs the average for each student.

Example 4:

#include <iostream>
using namespace std;
int main()
{
    char MTXchar[5][5] = {{'*','$','$','$','$'},
                          {'$','*','$','$','$'},
                          {'$','$','*','$','$'},
                          {'$','$','$','*','$'},
                          {'$','$','$','$','*'}};
                          
    for (size_t r = 0; r < 5; r++)
    {
        for (size_t c = 0; c < 5; c++)
        {
            
            if (c == r)
                cout << MTXchar[r][c];
            else
                cout << " ";
        }
        cout << endl;
    }
    return 0;
}

This code defines a 5×5 matrix (MTXchar) containing ” characters on the main diagonal and ‘$’ characters elsewhere. It then prints only the characters on the main diagonal, resulting in a diagonal line of ” characters.

Output:

The code outputs a diagonal line of ‘*’ characters on the console.

*    
 *   
  *  
   * 
    *

 

Passing a two-dimensional array to a function in C++ involves specifying the array as a parameter in the function declaration. Since a 2D array is essentially an array of arrays, you need to specify the size of the columns (since the rows are implicitly known based on the number of arrays).

  • Function Declaration:

When declaring a function that accepts a 2D array, you need to specify the array parameter along with the size of the columns. The size of the rows is not explicitly specified.

void functionName(int arr[][COLS], size_t rows, size_t cols) {
    // Function logic using arr
}

– int arr[][COLS]: This syntax indicates that the function takes a 2D array of integers with a specified number of columns (COLS).
– size_t rows: This parameter can be used to pass the number of rows in the array.
– size_t cols: This parameter can be used to pass the number of columns in the array

  • Function Call:

When calling the function, you need to provide the actual 2D array along with the number of rows and columns.

int myArray[ROWS][COLS];
functionName(myArray, ROWS, COLS);

– myArray: The name of the 2D array you want to pass.
– ROWS: The number of rows in the array.
– COLS: The number of columns in the array.

Example 5:

#include <iostream>
using namespace std;
void f(int arr[][5], int r)
{
    for (size_t i = 0; i < r; i++)
    {
        for (size_t j = 0; j < 5; j++)
        {
            cout << arr[i][j] << " ";
        }
        cout << endl;
    }
}
int main()
{
    int a[2][5] = {1,2,3,4,5,
                   10,20,30,40,50};
    f(a, 2);
    return 0;
}

The function f takes a 2D array (arr) and its number of rows (r) as parameters.
It uses nested loops to iterate over each element of the array and prints the elements in a tabular form.

The main function calls the function f with the 2D array a and the number of rows (2) as arguments.

Output:

The output of this code would be the elements of the 2D array a printed in a tabular form.

The printed output would look like:

1 2 3 4 5 
10 20 30 40 50 
  • Transpose matrix

The transpose of a matrix is an operation that flips the matrix over its diagonal, switching the row and column indices of the matrix. In other words, if the original matrix has elements at position (i, j), the transposed matrix will have the element at position (j, i).

Example 6:

#include <iostream>
using namespace std;
int main()
{
    int arr[3][3];
    for (size_t i = 0; i < 3; i++)
    {
        for (size_t j = 0; j < 3; j++)
        {
            cin >> arr[i][j];
        }
    }
    cout << "Matrix is: \n";
    for (size_t i = 0; i < 3; i++)
    {
        for (size_t j = 0; j < 3; j++)
        {
            cout << arr[i][j] << " ";
        }
        cout << endl;
    }
    cout << "Transpose matrix is:\n";
    for (size_t i = 0; i < 3; i++)
    {
        for (size_t j = 0; j < 3; j++)
        {
            cout << arr[j][i] << " ";
        }
        cout << endl;
    }

    return 0;
}

This code takes user input for a 3×3 matrix, prints the original matrix, and then prints its transpose.

Here are the key points:

  1. Input:
    The nested loops take user input for a 3×3 matrix.
  2. Original Matrix Output:
    After taking input, the code outputs the original matrix.
  3. Transpose Matrix Output:
    Another set of nested loops outputs the transpose of the matrix. It switches the row and column indices.

Example Output:

If the user enters:

1 2 3
1 2 3
1 2 3

The output would be:

Matrix is: 
1 2 3 
1 2 3 
1 2 3 
Transpose matrix is:
1 1 1 
2 2 2 
3 3 3

 

Share this

Two Dimensional Array

Or copy link

CONTENTS
English