How can I get a minimum value in c?

146 views Asked by At

I have created a code that calculates the sum, average, highest and lowest scores of the entered scores. I made sure that if score[i] is larger than max, socre[i] becomes max, and if it is smaller than min, socre[i] becomes min. I think I set the initial value correctly and set the conditional expression correctly, but the value of min is not correct. There are no grammatical errors. Could you tell me the wrong point?

#include <stdio.h>
int main(){
    
    int score[5];
    int sum = 0;
    int i,j;
    int max = score[0];
    int min = score[0];
    
    for(i=0; i<5; i++){
        scanf(" %d", &score[i]);
        sum += score[i];
        
        if  (max < score[i]){
            max = score[i];
        }
            if  (min > score[i]){
            min = score[i];
        }
    }
    
    printf("total = %d\nmean = %.2f\nmax = %d\nmin = %d\n%s\n", sum, (float)sum/5.0, max, min, sum<100 ? "Fail." : "Pass." );
    return 0;
}
1

There are 1 answers

0
Fe2O3 On

Good try. The comments below your question describe the problem of uninitialised variables.

Without resorting to INT_MIN and its brother, there's another way to achieve your objective:

#include <stdio.h>

#define N 5 // Use tokens. Don't repeat magic numbers in code

int main( void ){
    
    int score[ N ] = { 0 }; // initialise the array
    int sum = 0;
    int max = 0;
    int min = 0;
    
    for( int i = 0; i < N; i++ ) {
        scanf(" %d", &score[i]); // ToDo: validate scanf return value
        sum += score[i];
        
        if( score[max] < score[i] ) // assign the INDEX, not the VALUE
            max = i;

        if( score[min] > score[i] ) // and again.
            min = i;
    }
    
    printf(
        "total = %d\n"
        "mean = %.2f\n"
        "max = %d\n"
        "min = %d\n"
        "%s\n",
            sum,
            (float)sum/N,
            score[max], // retrieve value
            score[min],
            sum < 100 ? "Fail." : "Pass."
        );

    return 0;
}

By focussing on the index instead of the value, both min and max are current as soon as the first value has been stored into the array.

An advantage of this technique (if you will do more with the array values later) is that the datatype is not tied to INT_MIN & co. If the code is changed to take in unsigned char values, INT_MIN would be another maintenance point.

One last comment. Swap the conditional around:

        if( score[i] > score[max] )  max = i; // new max found
        if( score[i] < score[min] )  min = i; // new min found

It just reads better.