Write a function that computes the average value of an array of floating-point data: double average(double* a, int size) In the function, use a pointer variable, not an integer index, to traverse the array elements.

Respuesta :

Answer:

I am writing the function in C++. Let me know if you want the program in some other programming language. Her is the function.

double average(double* a, int size)

{ double sum = 0;

double avg;

for (int i = 0; i < size; i++){

   sum = sum + *a;    

   a++;  }

avg = sum/size;

return avg; }

Explanation:

First statement is the function definition of a average function which has two parameters, a and size. a is a pointer variable which is used as an index to traverse through the array and size is the size of the array.

Next the double type sum variable is declared and initialized to 0. This stores the sum of the array elements in order to computer average.

Next the double type avg variable is declared which returns the average value of an array.

Next the for loops starts which has a counter variable i which starts from 0 and the body of this loop will continue to execute until i variable reaches the end of the array which means i remains less than the array size. In the body of the loop, sum = sum + *a statement calculates the sum of each element of the array. a* is the pointer to each element of the array. This means a* gives access to the array element to which the a is currently pointing to.

a++ increments the position of the pointer by 1 and it keeps moving the pointer 1 position further until the loop ends. So this pointer is used in place of the integer index.

avg = sum/size; statement stores the average of the array elements into avg variable. avg is computed by dividing the total sum of the array elements to the size of the array.

return avg will finally returns the average value of an array.

We can write the main() function that will call the average() function to compute the average of the array values as follows:

int main()

{ int size = 6;

double array[] = {1.0,2.0,3.0,4.5,5.5,6.5};

double* a = array;

cout << average(a,size); }

The array[] has the following values 1.0, 2.0, 3.0, 4.5, 5.5, 6.5.

The pointer a points to the array elements of array[] instead of using index.

Then the average function is called which will compute the average value of the array[].

The output is:

3.75