Question: Problem 3: Following the supplied instructions, rewrite each function provided to you below so that it returns the same result but performs the operation in
Problem 3: Following the supplied instructions, rewrite each function provided to you below so that it returns the same result but performs the operation in a slightly different way.
a. Rewrite the following function so that it does not increment the variable ptr. Your new program must not use any square brackets, but must use an int variable to visit each double in the array. You may eliminate any unneeded variable.
double computeAverage(const double* scores, int nScores) { const double* ptr = scores; double total = 0; while (ptr != scores + nScores) { total += *ptr; ptr++; } return total/nScores; }
b. Rewrite the following function so that it does not use any square brackets (not even in the parameter declarations) but does use the integer variable k. Do not use any of the C-string functions such as strlen, strcpy, etc.
// This function searches through str for the last occurrence of the character chr. // If the chr is found at all, it returns a pointer into str where the character was last found. // Otherwise, it returns the value nullptr to designate that the character chr not found.
const char* findTheLastChar(const char str[], char chr) { const char * result = nullptr; for (int k = 0; str[k] != 0; k++) { if (str[k] == chr) { result = &str[ k ]; } } return result; }
c. Now rewrite the function shown in part b so that it uses neither square brackets nor any integer variables. Your new function must not use any local variables other than the parameters.
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
