Kathy Nguyen
Kathy Nguyen

Reputation: 1

Confused over while(cin >> x && x != 0) (when int x = 0) versus while(x != 0 && cin >> x ) (when int x = 1)

In my university's lecture today, we were given this:

input: 1, 2, 3, 0, 4

and two different codes

(1)

int x = 0;
int sum = 0;
int count = 0;
while (cin >> x && x != 0) {
    sum += x;
    count++;
}
cout  << static_cast<double>(sum) / count;

(2)

int x = 1;
int sum = 0;
int count = 0;
while (x != 0 &&  cin >> x ) {
    sum += x;
    count++;
}
cout  << static_cast<double>(sum) / count;

I understand the first code ends with an output of 2, but apparently the second output ends with an output of 1.5 (6/4). My confusion is over why the count is 4 if the loop becomes false after inputting zero - is it the location of the cin in the condition, the initialized x? I am confused. Thank you!

Upvotes: 0

Views: 621

Answers (3)

Aconcagua
Aconcagua

Reputation: 25526

What happens when you reach the zero?

while (cin >> x && x != 0)

You read in the zero and discover that x is 0. You will stop iteration.

while (x != 0 && cin >> x)

Now x is set to zero, but you have checked previous value of x, which hasn't yet been zero then. So you will enter the loop again:

sum += 0; // the current value of x
count++;  // one summand more

and only discover that x got zero when checking the loop condition in the subsequent loop run.

In other words, in second variant, you count the zero as additional summand.

Upvotes: 4

Caleth
Caleth

Reputation: 62704

In the second case, the loop is entered with x == 0. It stops after adding 0 to sum and incrementing count.

Upvotes: 1

Vlad from Moscow
Vlad from Moscow

Reputation: 310990

In the first loop the value 0 is not countered. While in the second loop the value 0 is countered in the variable count.

while (x != 0 &&  cin >> x ) { // <== 0 is read
    sum += x;
    count++;  // <-- and count is increased
}

In fact in the first loop the condition x != 0 is a pre-condition while in the second loop the condition is a post-condition.

The second loop can be equivalently rewritten (provided that the input was successfull) like

do
{
    cin >> x;
    sum += x;
    count++;
} while ( x != 0 );

Upvotes: 0

Related Questions