Reputation: 129
This is my code made to show the sum and average of an array using a for loop but when I run it it just outputs 0 for both the sum and average.
#include <stdio.h>
int main (void){
float grades[12] = {85.0, 77.0, 15.0, 100.0, 90.0, 98.0, 62.0, 84.0, 86.0, 70.0, 100.0, 99.0};
int counter;
float average;
float sum = 0.0;
for(counter = 0; counter == 12; counter++){
sum = sum + grades[counter];
}
average = sum/12;
printf("The sum of the grades is: %f \n", sum);
printf("The average of the grades are: %f \n", average);
system("pause");
}
Upvotes: 1
Views: 80
Reputation: 161
Your for
-loop is wrong. Try
for(counter = 0; counter < 12; counter++) {
...
}
Upvotes: 3
Reputation: 9172
for-loops are: for(init; while; increment)
Note that this is WHILE, not UNTIL
Your loop will never run:
for(counter = 0; counter == 12; counter++){
because 0 is never equal to 12.
Upvotes: 3
Reputation: 78155
for
stops as soon as its condition is false. Your condition, counter == 12
, is false on the first iteration, so the loop never runs.
Upvotes: 2