0

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!

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • 3
    `int sum x = 0;` does not compile. – Max Langhof Sep 26 '19 at 15:00
  • `int x = 1;` vs `int x=0;` is only to avoid the second code to step over the loop. The first code could have `int x = 1;` and there would be no difference. Did they teach you how to use a debugger? – 463035818_is_not_an_ai Sep 26 '19 at 15:01
  • 1
    [How to debug small programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) – R Sahu Sep 26 '19 at 15:01
  • 2
    Related (possible duplicate): [How does C++ handle &&? (Short-circuit evaluation)](https://stackoverflow.com/questions/5211961/how-does-c-handle-short-circuit-evaluation). TL/DR: 1st loop doesn't count the number if read number is `0`, while the 2nd does. – Algirdas Preidžius Sep 26 '19 at 15:02

3 Answers3

4

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.

Aconcagua
  • 24,880
  • 4
  • 34
  • 59
1

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

Caleth
  • 52,200
  • 2
  • 44
  • 75
0

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 );
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335