I am passing an array of exam grades to the examAverage function along with the size of the array. When I printf the array contents in the for loop they are correct, but when they are added together the sum is wrong. Even if I printf immediately after I set double sum = 0, it says sum = 2. By the time the function is complete I get an extremely large number. Any help is appreciated.
double examAverage(int arr[], int size){
int i;
double exAvg=0;
double sum =0;
printf("Sum = %d\n", sum);
for (i = 0; i < size; ++i)
{
printf("Sum = %d\n", sum);
sum = arr[i];
}
exAvg = sum / size;
return exAvg;
}
Main
double examAverage(int arr[], int size);
printf("How many exam grades would you like to enter?\n");
scanf("%d", &examGrad);
int exams[examGrad];
printf("Enter exam grades \n");
for(int i=0; i<sizeof(exams)/sizeof(exams[0]); i++){
scanf("%d", &exams[i]);
}
double exAvg;
exAvg= examAverage(exams, examGrad);
printf("Exam average = %d", exAvg);
Output
How many exam grades to enter?
2
Enter exam grades
100
50
Sum = 2
Sum = 10
Sum = 1079574528
Exam Average = 1081159680
sum = arr[i];should besum += arr[i];, and change the printf as the below answer indicates