0
My problem about while loop!
int main() { int num = -2; int number; int total = 0; while (num <= 5) { cin >> number; total+=number; num=num+1; } cout << total << endl; What do total+=number; and num+1; work? How does num+1; work??
6 Answers
+ 2
Thanks a lot fellađ
+ 1
total+=number is another way of saying âadd ânumberâ to totalâ. It can also be written as âtotal=total+numberâ. The line ânum=num+1â is similar, you are adding 1 to ânumâ, which can also be written as ânum+=1â or even ânum++â. This will increment ânumâ until num is equal to 5, then afterwards, your console will print the total.
+ 1
I think you got me wrong.. I mean what's the point of them ? What will happen if I leave them off deliberately ? And what will happen if I write num=num+2:
+ 1
If you leave ânum=num+1â out of the loop, num will never increase, and always equal -2. If you leave out âtotal+=numberâ, then your cout line will print total as 0 since it was initialized as 0 and never changed. If you write ânum+=2â instead, num will reach 5 in the while loop more quickly.
+ 1
Thank you . Just one more questio.. how does num=num+1; work?? What is the reason of result of choosing another number instead of 1 , for num=num+1;
+ 1
So num is initialized as -2. When you add 1 (num=num+1), num then becomes -1, then 0, then 1, and adds one until num is equal to 5 (as defined in your while loop). This means your loop will run 7 times (-2 through 5 is a difference of 7). If you add 2 to num each time instead of 1, num will go from -2 to 0, then 2, then 4, and then stop. It wouldnât add 2 to num after 4 since the while loop only runs while num is less than or equal to 5 (and if you added 2 to 4, the result â6â is greater than five, so it stops at 4).
So to paraphrase, num=num+1 makes the loop run 7 times, but num=num+2 makes the loop run only 3 times.