I'm learning C, and I wrote a program that reads a list of numbers and provides the sum, max, min and mean of the list. The list ends when a negative number is typed.
#include <stdio.h>
#include <stdlib.h>
int main ()
{
int i, number, sum, divider, min, max;
double mean;
int addend[1000];
char s[80];
for (i=0; i>=0; i++) {
fgets (s, sizeof(s), stdin);
number = atoi(s);
addend[i]=number;
if (addend[i]>=0) {
continue;
}
else break;
}
divider=i;
i=i-1;
sum=addend[i];
while (i>=1) {
sum=sum+addend[i-1];
i=i-1;
}
printf("[SUM]\n%i\n", sum);
if (addend[0]<0) {
printf("[MIN]\n0\n\n[MAX]\n0\n\n[MEAN]\n0\n");
}
else {
mean=sum/divider;
i=divider-1;
min=addend[i];
while (i>=0) {
if (addend[i-1]<min) {
min=addend[i-1];
}
i=i-1;
}
max=addend[i];
while (i>=0) {
if (addend[i-1]>max) {
max=addend[i-1];
}
i=i-1;
}
printf("[MIN]\n%i\n\n[MAX]\n%i\n\n[MEAN]\n%f\n", min, max, mean);
}
return 0;
}
Everything works fine, except the max (if i type "3, 6, 8, 9, -1" the max is 1075314688). I already found a solution (if I write max=addend[divider-1]
on line 42 it works fine), but I'm trying to understand why the code I originally wrote doesn't work. I tried searching for the answer online but I didn't find anything.