chapter 9 - arrays - handout 3
TRANSCRIPT
-
8/13/2019 Chapter 9 - Arrays - Handout 3
1/4
8
Arrays as parameters to functions
(1)Arrays are always passed by reference to functions. So there no need to add the &symbol, which means that if the array is changed in the function, then it is alsochanged in the main.
(2)Functions cant return array.int[ ] copy (int list[ ], int size); invalid
Example:
#include
#includeusing namespace std;
void initialize (int arr[ ], int size);
void Copy(const int A[ ], int B[ ], int size);
int main(){
int list[10]={0}, X[10];
initialize(list, 10);
Copy(list, X, 10);
cout
-
8/13/2019 Chapter 9 - Arrays - Handout 3
2/4
9
Examples of Functions processing 1D array
void initializeArray(int list[], int listSize)
{
int index;
for (index = 0; index < listSize; index++)list[index] = 0;
}
void fillArray(int list[], int listSize){
int index;
for (index = 0; index < listSize; index++)
cin >> list[index];}
void printArray(const int list[], int listSize)
{
int index;
for (index = 0; index < listSize; index++)
cout
-
8/13/2019 Chapter 9 - Arrays - Handout 3
3/4
10
Enum and arrays
enum color {Red, Yellow, Blue};
double List[3];color C;
for (C=Red; C
-
8/13/2019 Chapter 9 - Arrays - Handout 3
4/4
11
Exercise:
Write a function named duplicate that takes an array of int, and the array size. The
function should check if the array has any duplicates and output an appropriate
message.
#include using namespace std;
void duplicate (int list[ ], int size);int main()
{
int list[10]={1,9,3,4,5,6,7,8,9,10};
duplicate(list, 10);system("pause");
return 0; }
void duplicate (int list[ ], int size)
{
int i,j; bool found=false;for(i = 0; i