My problem about while loop! | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
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??

24th Sep 2020, 9:13 PM
Ali_combination
Ali_combination - avatar
6 Answers
+ 2
Thanks a lot fella👍
24th Sep 2020, 9:58 PM
Ali_combination
Ali_combination - avatar
+ 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.
24th Sep 2020, 9:26 PM
NULL
NULL - avatar
+ 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:
24th Sep 2020, 9:28 PM
Ali_combination
Ali_combination - avatar
+ 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.
24th Sep 2020, 9:33 PM
NULL
NULL - avatar
+ 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;
24th Sep 2020, 9:37 PM
Ali_combination
Ali_combination - avatar
+ 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.
24th Sep 2020, 9:42 PM
NULL
NULL - avatar