I’m trying to find the minimum and maximum value of a given array with a size as a parameter and pointers for the min and max values. What am I doing wrong?
void FindMinMax(const int array[], int size, int* min, int* max)
{
int minVal = array[0];
int maxVal = array[0];
int i;
for (i = 1; i < size; i++) {
if (array[i] > maxVal) {
*max = array[i];
}
if (array[i] < minVal) {
*min = array[i];
}
}
return;
}
I tried inputting the size into the array in a new declaration, but that didn’t work and said it couldn’t be defined.
>Solution :
minVal and maxVal are not updated during the loop, so the comparisons are only ever made against the first element of the array. This means *min and *max will simply be the last value in the array greater than / less than the first element, not necessarily the largest value or smallest overall.
The local variables are redundant.
void FindMinMax(const int array[], int size, int *min, int *max)
{
if (size > 0)
*min = *max = array[0];
for (int i = 1; i < size; i++) {
if (array[i] > *max)
*max = array[i];
else if (array[i] < *min)
*min = array[i];
}
}