How could the size of an array be zero or even less than zero?
The two function parameters are different. Nothing forces callers to give you anything remotely similar to the size of the actual array:
double a[] = {1.0, 2.0, 3.0, 4.0, 5.0};
double *max = maximum(a, -235);
In this case the size of the array is 5, but I passed a completely random and bogus value for the size argument. One might expect a reasonable call to look like this:
double *max = maximum(a, sizeof a / sizeof *a);
But that's not something the function itself can control, so it needs to do a sanity check on the arguments:
double *maximum(const double *a, int size)
{
assert(a != NULL); // Validate the pointer as best we can
if (size <= 0)
return NULL; // "Empty" array
// ...
}
The array is considered to be empty because the maximum function trusts the caller not to be a complete idiot. As such, the maximum function assumes the size parameter is an accurate representation of the number of elements in the array that the caller wants to process. If that size is less than one, the assumption is that there are no elements.Do you think that this problem is not clearly defined so it wouldn't be worth solving it???
I think it's defined well enough to come up with a reasonable implementation.Because, inside the function we will have to use this variable to iterate through the whole array.
And what's meant by the "whole array"? Riddle me this, how do any of the calls to my sum function below not process the "whole array"from the function's perspective:
#include <iostream>
int sum(int a[], int size)
{
int sum = 0;
while (--size >= 0)
sum += a[size];
return sum;
}
int main()
{
int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
std::cout<< sum(a, 1) <<'\n';
std::cout<< sum(a, 2) <<'\n';
std::cout<< sum(a, 3) <<'\n';
std::cout<< sum(a, 4) <<'\n';
std::cout<< sum(a, 5) <<'\n';
std::cout<< sum(a, 6) <<'\n';
}