Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Trying to find the miminum and max value of an array with pointers

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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];            
    }                                   
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading