Schelts
Schelts

Reputation: 19

How to add a running total after each pass in the while loop

I need to figure out how to continuously add to the running total of avg mpg and divide by how many times it goes through.

#include <stdio.h> 
        
int main() { 
    int miles;
    int gallons;
    int mpg;
    int avg;
          
    while (miles != -1) {
        printf("Enter number of miles driven(-1 to quit): ");
        scanf("%d", &miles);
        printf("Enter gallons used: ");
        scanf("%d", &gallons);
        mpg = miles / gallons;
        avg = mpg;
              
        printf("MPG this trip: %d\n", mpg);
        printf("Avg MPG(so far): %d\n", avg);
    }
}

Upvotes: 0

Views: 128

Answers (1)

S M Fazaluddin
S M Fazaluddin

Reputation: 36

Okay so I think I got what you are trying to say, so first of all you should initialize avg = 0; and instead of changing avg = mpg; every time the loop runs you should do avg += mpg; so that it will add the previous values to next time the loop runs, Take another int to find the total average, initialize from 0 int t_avg = 0; and for next thing, dividing how many times it goes through you should take a variable and initialize it t = 0; and just increment t every time the loop runs so you will get the time loop goes on and you just have to divide it with avg.
And I would suggest you to use do while loop instead of while so that would be much better. Hope this is what you were looking for.

#include <stdio.h>

int main() {
    int miles;
    int gallons;
    int mpg;
    int avg = 0, t = 0,t_avg = 0;

    do {
        t++;
        printf("Enter number of miles driven(-1 to quit): ");
        scanf("%d", &miles);
        printf("Enter gallons used: ");
        scanf("%d", &gallons);
        mpg = miles / gallons;
        avg += mpg;
        t_avg = avg/t;
        // adding average every time and diving every time the loop runs
        printf("MPG this trip: %d\n", mpg);
        printf("Avg MPG(so far): %d\n", t_avg);
    }while(miles != -1);
}

Upvotes: 1

Related Questions