• Articles
• Tutorials
• Interview Questions
• Webinars

# 2D Array: Definition, Declaration, and Implementation

In this blog, you will learn what a two-dimensional array is and how we can define it in our code. Further, you will learn how we can alter 2D arrays by adding and removing elements. We will also cover the application of two-dimensional arrays.

Check out our YouTube video on C programming language for absolute beginners!

## What are 2D (Two-Dimensional) Arrays?

A 2D (two-dimensional) array is a data structure that stores elements in a grid-like format with rows and columns like a matrix. It is an array of arrays, where each element is itself an array. Each element in a 2D array is accessed by specifying both its row index and column index. This allows you to organize and access data in a more structured way compared to a simple one-dimensional array.

## Why Do We Need a 2D Array?

While 1D arrays offer efficient storage and access for linear data, it becomes difficult to represent complex structures like images, maps, and matrices. This is where we use 2D arrays. In two-dimensional arrays, data is stored in the form of rows and columns. Using this, we can efficiently access and manipulate the data, making it widely used in various fields like image processing, game development, scientific computing, and financial modeling. The grid-like structure of a 2D array is particularly useful for storing and manipulating data for matrices, spreadsheets, and game boards.

Do you want to jumpstart your career in computer programming? Enroll in our C Programming Course and gain the skills to succeed!

## Initialization of a 2D Array

Now, let’s understand the steps of how we can declare a two-dimensional array inside a program:

• For the declaration of a 2D array, we will first define the data type of the data we want to store inside the 2D array (int/float/char).
• Then, we will assign any relevant name to the array, followed by the size of the 2D array inside square brackets.
• The first bracket stores the number of rows, and the second bracket stores the number of columns we want inside a 2D array.
```// Syntax for declaring a 2D array:

data_type   array_name[rows][columns];```

Here is an example of a declaration of a 2D array. In this example, we have declared a 2D array of integer type with the name ‘matrix’ with size 3 rows and 4 columns:

`int matrix[3][4];`

Let us see how we can declare and initialize the 2D array in different programming languages:

• C++
```// Declaring a 2D array of size 3x4

int arr[3][4];

// Initializing values in the array

int arr[3][4] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};```
• Python
```# Declaring a 2D array of size 3x4 and initializing with zeros

arr = [[0 for j in range(4)] for i in range(3)]

# Initializing values in the array

arr = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]```
• Java
```// Declaring a 2D array of size 3x4

int[][] arr = new int[3][4];

// Initializing values in the array

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

## Printing the Elements in a 2D Array

Let’s see how we can print the elements of a two-dimensional array in C++:

```#include <iostream>

using namespace std;

int main() {

// Declare and initialize a 2D array

int matrix[3][4] = {

{1, 2, 3, 4},   // First row

{5, 6, 7, 8},   // Second row

{9, 10, 11, 12} // Third row

};

// Printing elements of the 2D array

cout << "Elements of the 2D array:" << endl;

for (int i = 0; i < 3; i++) {      // Loop through rows

for (int j = 0; j < 4; j++) {  // Loop through columns

cout << matrix[i][j] << " "; // Print each element followed by space

}

cout << endl; // Move to the next line after printing each row

}

return 0;

}```

Output :

```Elements of the 2D array:

1 2 3 4

5 6 7 8

9 10 11 12```

In the above code, we have first declared and initialized a 2D array (`matrix`) to iterate through the rows and columns, and we have used a nested ‘for’ loop to print the elements. The outer loop (iterator : i) iterates through rows, and the inner loop (`j`) iterates through columns. After printing all elements in a row, the iterator moves to the next line (`cout << endl;`) for the next element of the next row.

## Changing Elements in a 2D Array

Another way to change elements in a 2D array in C++ involves using user input to specify the row and column indices and the new value to assign to that particular element. Here’s an example:

```#include <iostream>

using namespace std;

int main() {

const int rows = 3;

const int columns = 4;

// Declaring and initializing a 2D array

int matrix[rows][columns] = {

{1, 2, 3, 4},

{5, 6, 7, 8},

{9, 10, 11, 12}

};

// Displaying the original 2D array

cout << "Original 2D Array:" << endl;

for (int i = 0; i < rows; ++i) {

for (int j = 0; j < columns; ++j) {

cout << matrix[i][j] << " ";

}

cout << endl;

}

// Changing an element based on user input

int row_to_change, column_to_change, new_value;

cout << "\nEnter row index (0-" << rows - 1 << "): ";

cin >> row_to_change;

cout << "Enter column index (0-" << columns - 1 << "): ";

cin >> column_to_change;

cout << "Enter new value: ";

cin >> new_value;

// Check if the indices are within the array bounds

if (row_to_change >= 0 && row_to_change < rows && column_to_change >= 0 && column_to_change < columns) {

matrix[row_to_change][column_to_change] = new_value;

// Displaying the modified 2D array

cout << "\nModified 2D Array:" << endl;

for (int i = 0; i < rows; ++i) {

for (int j = 0; j < columns; ++j) {

cout << matrix[i][j] << " ";

}

cout << endl;

}

} else {

cout << "\nInvalid indices! Please enter valid indices within the array bounds." << endl;

}

return 0;

}```

In the above code, first, we have taken the value of the row and column to which we want the new value to be assigned and the value to be added to that index. Then, we will check if the entered index lies in the range or not. Now, the old number will be replaced by the number we entered earlier. Finally, we will display the new 2D array.

Output:

```Original 2D Array:

1 2 3 4

5 6 7 8

9 10 11 12

Enter row index (0-2): 1

Enter column index (0-3): 2

Enter new value: 3

Modified 2D Array:

1 2 3 4

5 6 3 8

9 10 11 12```

## Adding New Elements to a 2D Array

Here’s an example in C++ that demonstrates how to add new elements to a 2D array dynamically:

```#include <iostream>

using namespace std;

int main() {

const int initialRows = 3;

const int initialCols = 3;

// Initializing a 2D array with initial elements

int matrix[initialRows][initialCols] = {

{1, 2, 3},

{4, 5, 6},

{7, 8, 9}

};

int newRows, newCols;

cout << "Enter the number of rows to add: ";

cin >> newRows;

cout << "Enter the number of columns to add: ";

cin >> newCols;

// Creating a new temporary matrix with increased size

int tempMatrix[initialRows + newRows][initialCols + newCols];

// Copying existing elements to the temporary matrix

for (int i = 0; i < initialRows; ++i) {

for (int j = 0; j < initialCols; ++j) {

tempMatrix[i][j] = matrix[i][j];

}

}

// Adding new elements to the temporary matrix for the new rows and columns

for (int i = 0; i < newRows; ++i) {

for (int j = 0; j < initialCols + newCols; ++j) {

cout << "Enter element at position (" << initialRows + i << ", " << j << "): ";

cin >> tempMatrix[initialRows + i][j];

}

}

for (int i = 0; i < initialRows + newRows; ++i) {

for (int j = 0; j < newCols; ++j) {

cout << "Enter element at position (" << i << ", " << initialCols + j << "): ";

cin >> tempMatrix[i][initialCols + j];

}

}

// Updating the original matrix with the new size and elements

for (int i = 0; i < initialRows + newRows; ++i) {

for (int j = 0; j < initialCols + newCols; ++j) {

matrix[i][j] = tempMatrix[i][j];

}

}

// Displaying the updated 2D array

cout << "\nUpdated 2D Array:" << endl;

for (int i = 0; i < initialRows + newRows; ++i) {

for (int j = 0; j < initialCols + newCols; ++j) {

cout << matrix[i][j] << " ";

}

cout << endl;

}

return 0;

}```

In the above program, firstly the user will input any number of rows and columns to add to the existing 3×3 2D array (`matrix`). This program then dynamically creates a new temporary matrix (`tempMatrix`) of the new increased size. Elements of the original array are copied to the new array. Then, users are asked to input new elements. After this, these new elements are placed in newly added rows or columns. Finally, it displays the updated 2D array.

Output :

```Enter the number of rows to add: 1

Enter the number of columns to add: 0

Enter element at position (3, 0): 1

Enter element at position (3, 1): 1

Enter element at position (3, 2): 1

Updated 2D Array:

1 2 3

4 5 6

7 8 9

1 1 1```

## Removing  Elements from a 2D Array

In C++, removing elements from a 2D array is not easy, as arrays have a fixed size once declared. However, you can remove elements by creating a new array without the elements you want to remove and copying the desired elements to this new array.

Here is the code for the removal of elements from a 2D array by copying the desired elements to a new array:

```#include <iostream>

using namespace std;

int main() {

const int rows = 3;

const int cols = 3;

// Initializing a 2D array with initial elements

int matrix[rows][cols] = {

{1, 2, 3},

{4, 5, 6},

{7, 8, 9}

};

int rowToRemove, colToRemove;

cout << "Enter the row number to remove: ";

cin >> rowToRemove;

cout << "Enter the column number to remove: ";

cin >> colToRemove;

if (rowToRemove >= 0 && rowToRemove < rows && colToRemove >= 0 && colToRemove < cols) {

// Creating a new temporary matrix with reduced size

int tempMatrix[rows - 1][cols - 1];

int tempRow = 0, tempCol = 0;

// Copying elements to the temporary matrix, skipping the specified row and column

for (int i = 0; i < rows; ++i) {

if (i == rowToRemove) {

continue; // Skip the row to remove

}

tempCol = 0; // Reset temporary column index

for (int j = 0; j < cols; ++j) {

if (j == colToRemove) {

continue; // Skip the column to remove

}

tempMatrix[tempRow][tempCol++] = matrix[i][j];

}

++tempRow;

}

// Update the original matrix with the new size and elements

for (int i = 0; i < rows - 1; ++i) {

for (int j = 0; j < cols - 1; ++j) {

matrix[i][j] = tempMatrix[i][j];

}

}

// Displaying the updated 2D array

cout << "\nUpdated 2D Array:" << endl;

for (int i = 0; i < rows - 1; ++i) {

for (int j = 0; j < cols - 1; ++j) {

cout << matrix[i][j] << " ";

}

cout << endl;

}

} else {

cout << "\nInvalid row or column number! Please enter valid indices within the array bounds." << endl;

}

return 0;

}```

This code asks the user to input the row and column numbers of the element to remove. It creates a new temporary matrix (`tempMatrix`) with a reduced size by skipping the specified row and column, then the elements of the original matrix are updated based on the temporary matrix, effectively “removing” the specified row and column. Finally, it displays the updated 2D array.

Output :

```Enter the row number to remove: 1

Enter the column number to remove: 1

Updated 2D Array:

1 3

7 9```

## Matrix Multiplication of a 2D Array

Matrix multiplication is a mathematical operation where two matrices are multiplied to produce a new matrix. Matrix multiplication is done by multiplying the rows of the first matrix by the columns of the second matrix to get the elements of the resulting matrix. For example, while multiplying matrix A (m x n) with matrix B (n x p), the resulting matrix will be of (m x p).

Here is the code in C++ for matrix multiplication of 2D arrays:

```#include <iostream>

using namespace std;

const int ROWS_A = 3;

const int COLS_A = 2;

const int ROWS_B = 2;

const int COLS_B = 4;

void multiplyMatrices(int matA[][COLS_A], int matB[][COLS_B], int result[][COLS_B]) {

for (int i = 0; i < ROWS_A; ++i) {

for (int j = 0; j < COLS_B; ++j) {

result[i][j] = 0;

for (int k = 0; k < COLS_A; ++k) {

result[i][j] += matA[i][k] * matB[k][j];

}

}

}

}

int main() {

int matrixA[ROWS_A][COLS_A] = {{1, 2}, {3, 4}, {5, 6}};

int matrixB[ROWS_B][COLS_B] = {{7, 8, 9, 10}, {11, 12, 13, 14}};

int resultMatrix[ROWS_A][COLS_B];

// Multiply matrices A and B

multiplyMatrices(matrixA, matrixB, resultMatrix);

// Display the resulting matrix

cout << "Resulting Matrix (Matrix A x Matrix B):" << endl;

for (int i = 0; i < ROWS_A; ++i) {

for (int j = 0; j < COLS_B; ++j) {

cout << resultMatrix[i][j] << " ";

}

cout << endl;

}

return 0;

}```

Output :

```Resulting Matrix (Matrix A x Matrix B):

29 32 35 38

65 72 79 86

101 112 123 134```

Let’s understand the procedure for the above code:

• The `multiplyMatrices` function performs matrix multiplication by iterating through the rows and columns of the resulting matrix. It calculates each element by performing a dot product between the corresponding row from matrix A and the corresponding column from matrix B.
• `matrixA` and `matrixB` are two matrices to be multiplied.
• `resultMatrix` stores the result of the matrix multiplication.
• After multiplication, the resulting matrix is displayed.

You must keep in mind while coding that the dimensions of the matrices are compatible with multiplication, which means the number of columns in matrix A should be equal to the number of rows in matrix B for successful matrix multiplication.

Check out C++ Interview Questions to crack your next interview!

## Applications of 2D Arrays

There are various applications of two-dimensional arrays in solving programming problems in several domains due to their ability to represent and manipulate grid-like structures. Here are some of the most popular applications of two-dimensional arrays:

• Image Processing: In image processing, images are represented as 2D arrays of pixels. In algorithms, 2D arrays are required to perform operations like filtering, edge detection, resizing, and transformations by traversing through these arrays.
• Dynamic Programming: Problems like the knapsack problem, matrix chain multiplication, and longest common subsequence use 2D arrays to optimize recursive solutions.
• Board Games and Puzzles: Board games like chess, tic-tac-toe, and Sudoku often use 2D arrays to represent the game board.
• Dynamic Terrain Generation: In game development or simulations, 2D arrays are used to create and manage terrains, landscapes, or maps. These arrays help generate, store, and modify terrain data dynamically.

Don’t miss out on the latest programming trends and advancements; be part of Intellipaat’s Community today!

## FAQs

### How do you access elements in a 2D array?

Elements in a 2D array are accessed using row and column indices, such as `array[row][column]`.

### Can the size of a 2D array be changed dynamically?

In most programming languages, the size of a 2D array declared statically cannot be changed dynamically. However, dynamic memory allocation can be used to archive resizing.

### How does memory allocation work for 2D arrays?

2D arrays are usually allocated in a contiguous block of memory where elements are organized row-wise or column-wise, depending on the programming language.

### What are the differences between a 1D array and a 2D array?

A 1D array stores elements in a linear sequence, while a 2D array organizes elements in rows and columns, forming a grid-like structure.

### Are there any limitations or drawbacks to using 2D arrays in programming?

2D arrays have fixed sizes once declared. So it becomes very tough to resize them dynamically. They may also consume more memory for large dimensions compared to dynamic data structures. Additionally, accessing elements requires knowledge of specific indices, which can lead to errors if entered wrongly.

Course Schedule

Name Date Details
Python Course 22 Jun 2024(Sat-Sun) Weekend Batch
View Details
Python Course 29 Jun 2024(Sat-Sun) Weekend Batch
View Details
Python Course 06 Jul 2024(Sat-Sun) Weekend Batch
View Details