06_2D-Arrays_ITEC112_2022-23_Fall
06_2D-Arrays_ITEC112_2022-23_Fall
Introduction to Programming
2022 – 2023 Spring Semester
Arrays in Functions
&
2D Arrays
Passing an array to a function
• It is possible to send an array as an argument to a function.
Function name Array name Array size
showValues(myArrray);
return 0;
}
return arr;
}
Exercise 1
/* Arrays : Exercise-1
Write a program that asks the user to enter 3 quiz results from the
keyboard
and store them in an array. Having done so, calculate the average of
these
quizzes in a user defined function named: calculateAve.
The function prototype is : float calculateAve( int array[] );
*/
Exercise 1
#include <iostream>
using namespace std;
int main(void){
int mark[3];
return 0;
}
average = (float)sum/3;
return average;
}
Multi-Dimensional Arrays
• Multi dimensional arrays can be referred as “array of arrays”.
• For a Two - Dimensional (2D) array, we can visualise the elements
inside the array are stored in rows and columns.
• The total number of elements in a 2D array is calculated by
multiplying the row size (first dimension) with the column size
(second dimension).
• Two-dimensional arrays are often called matrices.
Structure of 2D Arrays
dataType arrayName[rowSize][columnSize]
d[0][0]=5;
d[0][1]=9; First Row (index 0) 5 9 4
d[0][2]=4;
d[1][0]=4;
d[1][1]=2; Second Row (index 1) 4 2 3
d[1][2]=3;
d[2][0]=8;
d[2][1]=6; Third Row (index 2) 8 6 1
d[2][2]=1;
int main(void){ 5 9 4
int b[3][3]={ {5,9,4}, {4,2,3}, {8,6,1} };
4 2 3
for( int i=0; i<3; i++ ){
for( int j=0; j<3; j++ ) 8 6 1
cout << b[i][j] << " ";
cout << endl;
}
return 0;
}
What happens
When the assigned values do not fill the size of the array?
The rest of the values are accepted as zero.
double rate[3][2] = { {0.075, 0.080} };
Column 0 Column 1
return 0;
}
What is the output of the following program?
[0] [1] [2]
#include <iostream>
using namespace std; C
[0] m
int main(void){
char letter[3][3] = { {'m', 'C'}, [1] t c e
{'t', 'c', 'e'},
{'p', 'n'}, };
[2] p n
cout << letter[0][1] <<
letter[0][0] << letter[2][0] <<
letter[1][2] << endl; Cmpe
return 0;
}
Trace the following program and write the output
#include <iostream> 1 2
using namespace std;
int main(void){ 4 5
int a[10][10], x=0;
for( int i=0; i<3 ;i++ ){
for( int h=0; h<2; h++ ){
a[i][h] = x+1;
x = x+1;
if( a[i][h] == 3 )
break;
cout<< a[i][h] << "\t";
}
cout<<endl;
}
return 0;
}
Exercise 5
• Write a program which will store the following values in a 2D array
and display “1” for an odd number and “0” for an even number.
1 2 3 4 5 1 0 1 0 1
6 7 8 9 10 0 1 0 1 0
11 12 13 14 15 1 0 1 0 1
16 17 18 19 20 0 1 0 1 0
21 22 23 24 25 1 0 1 0 1