#include <iostream.h> /***************************************************************** File: array2.C An example of an array being passed to a function This program stores integers in an array and computes their average *****************************************************************/ int const MAX_SIZE=5; int main() { int scores[MAX_SIZE] = {5, 5, 12, 17, 11}; float aver_data(int[], int ); float avg = aver_data(scores, MAX_SIZE); cout << "Average: " << avg << endl; return(0); } float aver_data(int numbers[], int size) { int i, sum; for(i=0, sum=0; i<size; i++) { cout << "score " << i+1 << " = " << numbers[i] << endl; sum += numbers[i]; } return (float(sum)/i); }
Output: score 1 = 5 score 2 = 5 score 3 = 12 score 4 = 17 score 5 = 11 Average: 10
#include <iostream.h> /********************************************************** File: array4.C This program demonstrates that arrays are passed by reference **********************************************************/ const int MAX_SIZE=5; int main() { int i; int scores[MAX_SIZE] = {5, 5, 12, 17, 11}; void change_data(int[], int ); cout << "Before the function call...\n"; for (i=0; i<MAX_SIZE; i++) cout << "scores[" << i << "] = " << scores[i] << endl; change_data(scores, MAX_SIZE); cout << "After the function call...\n"; for (i=0; i<5; i++) cout << "scores[" << i << "] = " << scores[i] << endl; return(0); } void change_data(int numbers[], int size) { int i; for(i=0; i<size; i++) { numbers[i] += 10; } }
Output: Before the function call... scores[0] = 5 scores[1] = 5 scores[2] = 12 scores[3] = 17 scores[4] = 11 After the function call... scores[0] = 15 scores[1] = 15 scores[2] = 22 scores[3] = 27 scores[4] = 21