Member-only story
In C++, create a method to compute the average of an array using pointers
Question
Create a method that have 2 parameters. The first parameter is an array of the data type ‘double’ called scores. The second parameter is an ‘int’ of the number of scores, the length of the array.
Explanation
Within the method ‘computeAverage’, first initialize a pointer called ‘ptr’ to point to the first element of the array, scores. Iterate through the elements of the array in scores array with a for loop. Within the for loop, keep adding the values of the array, element by element. The value of the element is retrieved by the ‘*’ symbol, therefore written as ‘*(ptr+i)’. Once the program exits out of the for loop, divide the sum of the elements ‘tot’ with the length of the array, nScores.
Solution
#include <iostream>using namespace std;double computeAverage(const double* scores, int nScores){const double* ptr = scores;double tot = 0;for (int i=0; i<nScores; i++){
//ptr+i is to iterate through the pointers of the array, and '*' is //used to get the VALUE of where the pointer is pointing attot = tot + *(ptr+i); }return tot/nScores;}int main(){