April Parker
April Parker

Reputation: 111

How do I stop a counter variable that keeps counting values from previous for loops? C Program

I am stuck on the last part of my homework assignment and hope I can get some guidance on what to do. The assignment is simple, I create a program that asks a user to input test scores until they type in my sentinel value of -1. Then the output displays the average of all imputed scores, this is to be repeated 4 times then the program exits. Everything works except my counter value. The counter keeps counting imputed scores from both the previous and current loops instead of only the current loop. So in iteration 2 it is giving me the average of all inputs from the first loop and the current loop.

Note: I haven't learned about arrays or anything else super advance yet.

I already initialized the count variable to 0 but I am can't seem to figure out why it ins't resetting per each loop. I moved the count=0 after the loop and before the loop and that doesn't do anything.

#include <stdio.h>
float calculateAverage(float, float);
FILE *fp;

int main(void)
{
    int i;
    float avg, score, sum = 0, count = 0;

    fopen_s(&fp, "csis.txt", "w");
    printf("***Average of Inputed Grades***\n");
    for (i = 1; i <= 4; ++i)
    {
        do
        {
            printf("\nEnter Test Scores or -1 for average\n");
            scanf_s("%f", &score);
            fprintf(fp, "\nEnter Test Scores or -1 for average\n%f\n", score);
            if (score != -1)
            {
                sum = sum + score;
                count++;
            }
        } while (score >= 0 && score <= 100 && score != -1);


        avg = calculateAverage(sum, count);
        printf("\nThe Average for the entered test scores is:%.2lf\n", avg);
        fprintf(fp, "\nThe Average for the entered test scores is:%.2lf\n", avg);
    }

    fclose(fp);
    getchar();
    return 0;
}

float calculateAverage(float sum, float count)
{
    float avg = sum / count;
    return (avg);
} 

Expected results should display the average of the imputed test scores only for the current iteration then reset itself upon the next iteration.

Upvotes: 0

Views: 1701

Answers (1)

dbush
dbush

Reputation: 224102

The sum and count variables aren't resetting after each iteration of the do...while loop because you don't explicitly do so. You do set them to 0 at the start of the function where they're first defined, but you don't reset them again anyplace else.

You need to set both to 0 before entering the do...while loop:

   for (i = 1; i <= 4; ++i)
    {
        sum = 0;
        count = 0;
        do
        {
           ...

Even better, define sum and count at this point (as well as avg and score) since they're not used outside of the for loop:

   for (i = 1; i <= 4; ++i)
    {
        float sum = 0, count = 0, avg, score;
        do
        {
           ...

Upvotes: 3

Related Questions