Question #267537

  1. Rewrite the following function so that it returns the same result, but does not increment the variable ptr. Your new program must not use any square brackets, but must use an integer variable to visit each double in the array. You may eliminate any unneeded variable.
    double mean(const double* scores, int numScores)
    {
        const double* ptr = scores;
        double tot = 0;
        while (ptr != scores + numScores)
        {
            tot += *ptr;
            ptr++;
        }
        return tot/numScores;
    }

Expert's answer

#include<iostream>
using namespace std;

double mean(const double* scores, int numScores)
{
	double tot = 0;
	for (int i = 0; i < numScores; i++)
	{ 
		tot += *(scores + i);
	}
	return tot / numScores;
}

int main()
{
	const int N = 5;
	const double scores[N] = { 1,3,6,8,10};
	cout << mean(scores, N);
}
LATEST TUTORIALS
APPROVED BY CLIENTS