// example of arrays, and functions using arrays #include using namespace std; void PrintArray(const int[] , const int); void SwapElements(int[] , int, int); int Sum(const int arr[], const int size); double Average(const int arr[], const int size); int Largest(const int arr[], const int size); int Smallest(const int arr[], const int size); int main() { int list1[5] = {2, 6, 9, -10, 12}; // array of 5 integers int i; // for loop indexing int list2[20]; // array size 20, uninitialized cout << "\nlist1 = "; PrintArray(list1, 5); cout << "\n"; // compute the sum of the list elements cout << "Sum of list1 elements = " << Sum(list1, 5) << '\n'; cout << "Average of list1 elements = " << Average(list1, 5) << '\n'; // initialize the array to 2, 4, 6, 8, 10, ... for (i = 0; i < 20; i++) list2[i] = 2 * i + 2; cout << "\nlist2 = "; PrintArray(list2, 20); // display the contents cout << '\n'; cout << "Sum of list2 elements = " << Sum(list2, 20) << '\n'; cout << "Average of list2 elements = " << Average(list2, 20) << '\n'; // create a third list, and get user to enter the data int list3[10]; cout << "Enter 10 integer values: "; for (i = 0; i < 10; i++) cin >> list3[i]; // user enter the items cout << "\nlist3 = "; PrintArray(list3, 10); // display the contents cout << '\n'; // find the largest element of list3 cout << "Largest number in list1 is: " << Largest(list1, 5) << '\n'; cout << "Largest number in list2 is: " << Largest(list2, 20) << '\n'; cout << "Largest number in list3 is: " << Largest(list3, 10) << '\n'; cout << "Smallest number in list1 is: " << Smallest(list1, 5) << '\n'; cout << "Smallest number in list2 is: " << Smallest(list2, 20) << '\n'; cout << "Smallest number in list3 is: " << Smallest(list3, 10) << '\n'; cout << "Swapping elements 4 and 7\n"; SwapElements(list3, 4, 7); cout << "\nlist3 = "; PrintArray(list3, 10); cout << "\n\n"; return 0; } void PrintArray(const int arr[], const int size) { int i; cout << "{ "; for (i = 0; i < size-1; i++) cout << arr[i] << ", "; cout << arr[size-1] << " }"; // print last item } void SwapElements(int arr[] , int a, int b) // swap arr[a] and arr[b] { int temp; temp = arr[a]; arr[a] = arr[b]; arr[b] = temp; } int Sum(const int arr[], const int size) { int total = 0; for (int i = 0; i < size; i++) total = total + arr[i]; return total; } double Average(const int arr[], const int size) { return Sum(arr, size) * 1.0 / size; } int Largest(const int arr[], const int size) { int max = arr[0]; // the answer SO FAR for (int i = 1; i < size; i++) if (arr[i] > max) max = arr[i]; return max; // largest number } int Smallest(const int arr[], const int size) { int min = arr[0]; // the answer SO FAR for (int i = 1; i < size; i++) if (arr[i] < min) min = arr[i]; return min; // largest number }