Hopelessdecoy
Hopelessdecoy

Reputation: 129

Why is my code outputting 0 when I run it? whats wrong and how do I fix it?

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

Answers (3)

philipp94831
philipp94831

Reputation: 161

Your for-loop is wrong. Try

for(counter = 0; counter < 12; counter++) {
    ...
}

Upvotes: 3

Tim
Tim

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

GSerg
GSerg

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

Related Questions