Académique Documents
Professionnel Documents
Culture Documents
Array (Part 2)
Learning Outcomes:
To know how to use array as function
parameter
1
Arrays and Functions
Using function to process arrays in large program
2
1- D array : Passing individual elements
Passing individual element
Array element must matches the function
parameter type
3
Passing individual element - Example 1
4
Passing an individual element - Example 2
#include <iostream>
using namespace std;
void main()
{
int i,j,ary1[4][3]={{1,2,3},{2,4,6},{3,6,9},{3,2,1}};
void print(int a)
{
cout << a << “\t“;
} // end print
5
1- D array : Passing the whole array
Passing the whole array
When we use large arrays in functions, by passing
each value we need an extra memory to do so
6
An array name is the address of the first element
in the array
void main()
{
int numbers[SIZE]={1,2,3,4,5,6,7};
reverseOrder(numbers, SIZE);
} // end main
10
2 ) Passing a two-dimensional array to function
Passing a row
Pass the whole row by indexing the array name with only the
row number
11
2 – D Array: Passing an individual element - Example
#include <iostream>
using namespace std;
void print(int a);
void main()
{
int i,j,ary1[4][3]={{1,2,3},{2,4,6},{3,6,9},{3,2,1};
}
}
void print(int a)
{
cout<<a<<“\t“;
}
12
2 – D Array : Passing a row - Example
13
2 – D Array : Passing the whole array – Example 1
14
2 – D Array : Passing the whole array - Example 2
#define NUMBER_OF_STUDENTS 5 // const int NUMBER_OF_STUDENTS=5;
#define NUMBER_OF_QUESTIONS 10 // const int NUMBER_OF_QUESTIONS=10;
void main()
{
char key[NUMBER_OF_QUESTIONS] =
{'C','C','B','A','D','B','A','B','C','D' };
char answer[NUMBER_OF_STUDENTS][NUMBER_OF_QUESTIONS]=
{
{'C','D','C','C','B','B','A','B','C','B'},
{'C','C','B','C','D','B','A','B','A','B'},
{'D','D','C','A','D','B','A','B','A','D'},
{'B','C','C','C','B','B','B','B','C','C'},
{'C','C','C','A','D','B','C','B','C','D'}
};
int checked[NUMBER_OF_STUDENTS];
} // end main
15
cont. eg. 2 – D Array : Passing the whole array
void checkAnswer(char key[], char answer[][NUMBER_OF_QUESTIONS],
int numStud, int numQues, int checked[])
{
int i, j; // declaring index
cout << "Student " << i << "'s marks : " << checked[i] <<
"/" << NUMBER_OF_QUESTIONS << "." << endl;
} // end for
} // end checkAnswer
- END - 16