Lab Manual (Lab 10 + 11)
Session: Spring 2020
School of Systems and Technology
UMT Lahore Pakistan
LAB INSTRUCTOR: AYESHA MAJID ALI
Contact:
[email protected] Room #: 504 Last cabin 4th floor SST
Objective
The objective of the lab is to understand the concept and how to implement two- and three-dimensional
arrays.
Multidimensional arrays In C++:
Multidimensional arrays are also known as array of arrays. The data in multidimensional array
is stored in a tabular form as shown in the diagram below:
Why do we use multidimensional arrays:?
name = customers[0][0]
email = customers[0][1]
dateofbirth = customers[0][2]
A two-dimensional array:
int arr[2][3];
This array has total 2*3 = 6 elements.
A three-dimensional array:
int arr[2][2][2];
This array has total 2*2*2 = 8 elements.
Two-dimensional array
Let’s see how to declare, initialize and access Two Dimensional Array elements.
How to declare a two-dimensional array?
int myarray[2][3];
Initialization:
We can initialize the array in many ways:
Method 1:
int arr[2][3] = {10, 11 ,12 ,20 ,21 , 22};
Method 2:
This way of initializing is preferred as you can visualize the rows and columns here.
int arr[2][3] = {{10, 11 ,12} , {20 ,21 , 22}};
Accessing array elements:
arr[0][0] – first element
arr[0][1] – second element
arr[0][2] – third element
arr[1][0] – fourth element
arr[1][1] – fifth element
arr[1][2] – sixth element
Example: Two dimensional array in C++
#include <iostream>
using namespace std;
int main(){
int arr[2][3] = {{11, 22, 33}, {44, 55, 66}};
for(int i=0; i<2;i++){
for(int j=0; j<3; j++){
cout<<"arr["<<i<<"]["<<j<<"]: "<<arr[i][j]<<endl;
}
}
return 0;
}
Output:
arr[0][0]: 11
arr[0][1]: 22
arr[0][2]: 33
arr[1][0]: 44
arr[1][1]: 55
arr[1][2]: 66
Lab Tasks
Task 1
Write a C++ program to find the sum and difference of two, two dimensional arrays of size 2*2.
Sample output: