AMIR PEDRAM
AMIR PEDRAM

Reputation: 9

finding average of numbers using while loop

I'm new to cpp and want to find the average of exam score using while loop, the number of student attended exam is not clear thats why i used while loop but it doesnt give the right answer.

int main() {

    int Average = 0;
    int x=0;
    int counter=0;
    int sum=0;
    
        while (x!=1) {
            cout << "enter a score";
            cin >> x;
             sum += x;
            ++counter;
            Average =  sum / counter;

        }       
}

Upvotes: 0

Views: 6183

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 596713

You are including the terminating 1 in the values of sum and counter, which is why you end up with the incorrect Average of 7:

10 + 10 + 10 + 1 = 31
31 / 4 = 7

Instead of the expected Average of 10:

10 + 10 + 10 = 30
30 / 3 = 10

You need to break the loop when 1 is entered, before you update sum and counter, eg:

int main() {

    int Average = 0;
    int x = 0;
    int counter = 0;
    int sum = 0;
    
    do {
        cout << "enter a score";
        if (!(cin >> x)) break; // <-- add this
        if (x == 1) break; // <-- add this
        sum += x;
        ++counter;
    }       
    while (true);

    if (counter != 0) // <-- add this
        Average =  sum / counter;
}

Upvotes: 2

Related Questions