15

Mar# Multi dimensional array in Data Structures

### Data Structures & Algorithms For Beginners Free Course

## Multi-dimensional Array: An Overview

In computer programming, data organization plays a crucial role in efficient algorithmic design and execution and Data Structures and Algorithms (DSA) provided it better way, enabling efficient problem-solving and algorithmic design. In this DSA tutorial, we'll explore the concept of multi-dimensional arrays, their characteristics, and their applications in DSA. You might have already come across arrays while learning arrays in C and arrays in C++.

To further enhance your understanding and application of array concepts, consider enrolling in the best Data Structures and Algorithms Course, where you can gain comprehensive insights into effective data structure utilization for improved problem-solving and time management.

What is a multi-dimensional array?

The powerful tool that programmers often uses for handling structured data is the multi-dimensional array. Unlike traditional one-dimensional arrays, multi-dimensional arrays provide a way to organize data in multiple dimensions, offering a more versatile and expressive approach to solving complex problems.

A multi-dimensional array is essentially an array of arrays, extending beyond the concept of a one-dimensional array. While a one-dimensional array is a linear collection of elements, a multi-dimensional array can be visualized as a matrix or a grid, where data is arranged in rows and columns. Commonly used dimensions include two-dimensional (2D) arrays, three-dimensional (3D) arrays, and even higher-dimensional arrays.

#### syntax

` `` array_name[size1][size2]....[sizeN];`

- data_type: The data type that will be stored in the array.
- array_name: The array's name.
- size1, size2,..., sizeN: Dimensional sizes.

## Common operations on Multidimensional array

### 1. Accessing Elements

Retrieving the value stored at a specific position within the multi-dimensional array. This involves providing the indices corresponding to the desired element's location. In a 2D array, for example, access might be performed using array[row][column].

`int value = array[2][3];`

### 2. Insertion and Modification

Changing the value of an existing element or inserting a new element at a particular position in the array.

`array[1][2] = 42;`

### 3. Initialization

Assigning initial values to the elements of the array during its creation or later in the program.

` ``int array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]; `

### 4. Traversal

Iterating through all elements of the multi-dimensional array to perform operations on each element. This is often done using nested loops, one for each dimension.

` ````
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
// Perform operations on array[i][j]
}
}
```

### 5. Search

Finding the position or value of a specific element within the array.

` ``index = next((i, j) for i, row in enumerate(array) for j, val in enumerate(row) if val == 42)`

### 6. Deletion

Removing elements from the array. Note that in many programming languages, resizing a multi-dimensional array might involve creating a new array and copying the desired elements.

` ````
array[1][2] = 0; // Set the value to a default or placeholder value
```

### 7. Transpose

Creating a new array where the rows and columns are swapped. This is a common operation in linear algebra.

` ````
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
transposed[j][i] = array[i][j];
}
}
```

### 8. Matrix Multiplication

Specific to 2D arrays, matrix operations such as addition, subtraction, and multiplication are common.

` ````
result = [[sum(a * b for a, b in zip(row, col)) for col in zip(*matrix2)] for row in matrix1]
```

**Read More - Data Structure Interview Questions for Experienced**

## Examples of Two-dimensional Array

Below is an example of a two-dimensional array in Java, representing a matrix and performing a simple operation on it:

```
def main():
# Declare and initialize a 2D array (3x3 matrix)
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
# Print the original matrix
print("Original Matrix:")
print_matrix(matrix)
# Example operation: Multiply each element by 2
multiply_matrix_by_scalar(matrix, 2)
# Print the modified matrix
print("\nModified Matrix (multiplied by 2):")
print_matrix(matrix)
# Function to print a 2D matrix
def print_matrix(matrix):
for row in matrix:
for element in row:
print(element, end=" ")
print()
# Function to multiply each element of the matrix by a scalar
def multiply_matrix_by_scalar(matrix, scalar):
for i in range(len(matrix)):
for j in range(len(matrix[0])):
matrix[i][j] *= scalar
if __name__ == "__main__":
main()
```

```
public class MultiDimensionalArrayExample {
public static void main(String[] args) {
// Declare and initialize a 2D array (3x3 matrix)
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Print the original matrix
System.out.println("Original Matrix:");
printMatrix(matrix);
// Example operation: Multiply each element by 2
multiplyMatrixByScalar(matrix, 2);
// Print the modified matrix
System.out.println("\nModified Matrix (multiplied by 2):");
printMatrix(matrix);
}
// Function to print a 2D matrix
private static void printMatrix(int[][] matrix) {
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
// Function to multiply each element of the matrix by a scalar
private static void multiplyMatrixByScalar(int[][] matrix, int scalar) {
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
matrix[i][j] *= scalar;
}
}
}
}
```

```
#include
// Function prototypes
void printMatrix(int matrix[3][3]);
void multiplyMatrixByScalar(int matrix[3][3], int scalar);
int main() {
// Declare and initialize a 2D array (3x3 matrix)
int matrix[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Print the original matrix
std::cout << "Original Matrix:" << std::endl;
printMatrix(matrix);
// Example operation: Multiply each element by 2
multiplyMatrixByScalar(matrix, 2);
// Print the modified matrix
std::cout << "\nModified Matrix (multiplied by 2):" << std::endl;
printMatrix(matrix);
return 0;
}
// Function to print a 2D matrix
void printMatrix(int matrix[3][3]) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
std::cout << matrix[i][j] << " ";
}
std::cout << std::endl;
}
}
// Function to multiply each element of the matrix by a scalar
void multiplyMatrixByScalar(int matrix[3][3], int scalar) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
matrix[i][j] *= scalar;
}
}
}
```

#### Output

```
Original Matrix:
1 2 3
4 5 6
7 8 9
Modified Matrix (multiplied by 2):
2 4 6
8 10 12
14 16 18
```

## Applications in DSA

### Matrix Operations

Multi-dimensional arrays, especially 2D arrays, are extensively used in solving matrix-related problems. Matrix multiplication, addition, inversion, and other operations crucial in linear algebra find straightforward implementation through multi-dimensional arrays.

### Dynamic Programming

Dynamic programming, a key paradigm in algorithm design, often involves solving problems by breaking them down into subproblems and storing the results. Multi-dimensional arrays serve as dynamic programming tables, enabling efficient memorization and reducing redundant computations.

### Graph Algorithms

Graph-related problems frequently utilize 2D arrays to represent adjacency matrices. Whether traversing graphs, finding shortest paths, or detecting cycles, multi-dimensional arrays provide an organized and efficient means to represent and process graph structures.

### Image Processing

In DSA, multi-dimensional arrays are employed for image manipulation and processing. Pixel values in images can be stored in 2D arrays, allowing for efficient application of filters, transformations, and other image-processing algorithms.

##### Summary

Multi-dimensional arrays evolve as a flexible and efficient tool in the developing environment of Data Structures and Algorithms. This article briefly describes the multi-dimensional array in DSA. We talked about its definition, syntax, declaration, and initialization. We hope this tutorial has helped you understand the one-dimensional array problem in C. You can quickly store and access data in a structurally consistent manner by utilizing an array. This will help make your code more efficient and improve your skills as a programmer.

## FAQs

### Q1. What is a multi-dimensional array?

### Q2. How are multi-dimensional arrays represented in programming languages?

**type name[row_size][column_size]**. In Python, it can be implemented using nested lists, while in MATLAB, multi-dimensional arrays are the fundamental data structure.

### Q3. What are common use cases for multi-dimensional arrays?

### Q4. How do you access elements in a multi-dimensional array?

**array[row_index][column_index]**to access a specific element.