+ 2

How come you have to put “cin” in the while loop? C++

I am relatively new to programming in C++ and programming in general, but something has been bugging me. How come this is okay. int count = 0; int total = 0; int number; while (count < 5) { cin >> number; total += number; count++; } But not this? int count = 0; int total = 0; int number; cin >> number; while (count < 5) { total += number; count++; ) Was this mentioned in the lessons? Why should the cin be inside the loop? Wouldn’t the output be the same if the value was evaluated before the loop? Help!

19th Jan 2019, 5:47 AM
Cookie Coder
Cookie Coder - avatar
3 odpowiedzi
+ 12
Both actually work fine. The semantics are however different. The first example allows you to input five numbers (adding each to total), while the second example allows you to input only once (and adds the same input value to total for five times). Also, you probably meant to do += and not =+ P.S. Putting cin in loop blocks do not work well with Code Playground. You will need to compile and run it on a desktop to see the difference.
19th Jan 2019, 5:48 AM
Hatsy Rei
Hatsy Rei - avatar
+ 3
when cin >> number; is inside the while loop, user is being asked to provide input every time the loop is performed, i.e. 5 times in your example. when cin << line is outside the while loop, user is only asked once and the same number is used inside the while loop. in your example, it is equivalent to number * 5
19th Jan 2019, 3:02 PM
Mel C
+ 1
in the first loop, you need to enter number 5 times per loop. in the second one you are getting total value increased by same number all the time.
19th Jan 2019, 5:17 PM
Edin Hajdarevic
Edin Hajdarevic - avatar