You are on page 1of 17

Data Structures

Multi- Demensional Arrays


Multi-dimensional array
 A multi-dimensional array is an array of arrays.
 It can be two dimensional or three dimensional.
 The data is stored in tabular form (row ∗ column) which
is also known as matrix
 There are no restrictions on the array's dimensions.
Multi-dimensional array
 For 1D array elements are addressed by specifying one
index
 A[i]
 For multi dimensional arrays each element is identified by
a tuple of indexes (as many as the number of dimensions)
 A[i][j]
 B[i][j][k]
Elements in array
 Two Dimensional Array
 A[i][j]
 A[2][3]
 Number of elements = 2*3
 Number of elements = 6
 Multi Dimensional Array
 A[i][j][k]
 A[3][3][3]
 Number of elements = 3*3*3
 Number of elements = 9
Two Dimensional Array
Multi- Dimensional Array
 Three dimensional array of size 3x3x3
Initializing Multi-dimensional Array
 Two Dimensional Array
 A[i][j] = A[rows][columns]
 A[2][3] = {{10, 11 ,12} , {20 ,21 , 22}};

 Multi Dimensional Array


 A[i][j][k] = A[layers][rows][columns]
 A[2][3][2] = { { {1,-1}, {2, -2}, {3, -3}},

{ {4, -4}, {5, -5}, {6, -6}}}


Layer 1: [ [1, -1], [2, -2], [3, -3] ]
Layer 2: [ [1, -1], [2, -2], [3, -3] ]
Two Dimensional Array
Three Dimensional Array
Taking input from user
Adding two 2D Arrays
Adding two 2D Arrays
1. Declare and initialize 2 two-dimensional arrays a and b.
2. Calculate the number of rows and columns present in
the array
3. and store it in variables rows and cols respectively.
4. Declare another array sum with the similar dimensions.
5. Loop through the arrays a and b, add the corresponding
elements
e.g a11 + b11 = sum11
6. Display the elements of array sum
Adding two 2D Arrays
1. int rows, cols, i, j;
2. int a[rows][cols], b[rows][cols], sum[rows][cols];

//Enter Rows and Columns of Matrix


3. cin >> rows >> cols;
// Enter first Matrix of size rows x col
// Input first matrix
4. for(i = 0; i < rows; i++):
5. for(j = 0; j < cols; j++):
6. cin >> a[i][j];
end
end
Adding two 2D Arrays
// Input second matrix
7. for(i = 0; i < rows; i++):
8. for(j = 0; j < cols; j++):
9. cin >> b[i][j];
end
end
// adding both array
10. for(i = 0; i < rows; i++):
11. for(j = 0; j < cols; j++):
12. sum[i][j] = a[i][j] + b[i][j];
end
end
Advantages of Array
 Random access
 Code Optimization (less code)
 Efficient memory usage
 Easy to traverse data
 Easy to manipulate data
 Easy to sort data
Disadvantages of Array
 Lack of flexibility
 Difficulty in Inserting and Deleting Elements
 Inefficient for Search
Task to do
 Multiplying two 2D Arrays
 Finding transpose of a 3D Array
 Searching for an element in an matrix
 Extract even and odd numbers from a matrix and place
them in separate matrix each.
 Arrange matrix in ascending/descending order
 Multiplying a matrix by scalar.

You might also like