Вы находитесь на странице: 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 also changed in the main. (2) Functions cant return array. int[ ] copy (int list[ ], int size); invalid Example: #include <iostream> #include<iomanip> using 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<<"Data = "; for(int i = 0; i<10; i++) cout<<X[i]<<" "; system("pause"); return 0; } void initialize (int arr[ ], int size) { for(int i = 0; i<size; i++) arr[i]=i; } void Copy(const int A[ ], int B[ ], int size) { for(int i = 0; i<size; i++) B[i]=A[i]; }

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 << list[index] << " "; } int sumArray(const int list[], int listSize) { int index; int sum = 0; for (index = 0; index < listSize; index++) sum = sum + list[index]; return sum; } int indexLargestElement(const int list[], int listSize) { int index; int maxIndex = 0; //Assume the first element is the largest for (index = 1; index < listSize; index++) if (list[maxIndex] < list[index]) maxIndex = index; return maxIndex; }

10 Enum and arrays enum color {Red, Yellow, Blue}; double List[3]; color C; for (C=Red; C<=Blue; C=static_cast<color>(C+1) ) list[C]=0.0; list[Red] = list[Red]+3.5; //store 3.5 in list[0] Other ways of declaring arrays const int size = 10; typedef double list[size]; list A; //Defines an array of 10 double, which is equivalent to writing: double A[size];

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 <iostream> 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<size-1; i++) { for(j=i+1; j<size; j++) if(list[i]==list[j]) { found=true; break; } if(found==true) break; } if(found) cout<<"Duplicate"; else cout<<"No duplicate"; }

Вам также может понравиться