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;
}
Good try. The comments below your question describe the problem of uninitialised variables.
Without resorting to
INT_MINand its brother, there's another way to achieve your objective:By focussing on the index instead of the value, both
minandmaxare 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 inunsigned charvalues,INT_MINwould be another maintenance point.One last comment. Swap the conditional around:
It just reads better.