+ 2

Can someone please explain the while loop

int num = 1 int number; int total = 0 while ( num <= 2 ) { cin >> number; total += number; num++; } cout << total << endl; .... for instance if i enter num = 1, which is less than 2 so total=1 and num=2... then again since 2=2 therefore total=1+2=3 and num=3.. since 3 is greater than 2 therefore the loop ends. is it correct? shouldn't it give total=3??

18th Jan 2017, 10:16 PM
tayyab
6 Answers
+ 3
yes.. much appreciated bro
19th Jan 2017, 2:23 PM
tayyab
+ 2
So is "total" the total num of inputs or the sum of all the inputs?
19th Jan 2017, 12:08 AM
tayyab
+ 1
but when i run it it's giving total=2... can anyone please explain....
18th Jan 2017, 10:17 PM
tayyab
0
The num variable is different from the number variable right? The num will be used by the loop while number is a user input, and total is sum of number, which is a user input. Your loop will only run twice, since num is once, the loop will only run if num is smaller than or equals to 2, so if num is greater than 2, the loop will terminate. In each iteration, num will be incremented so the loop will run in 2 iteration(1++ --> 2++ --> 3). In each iteration, the code will ask for user input and asign it to the number variable, and add the number to the total variable. So the loop will print all the sum of user inputs, which is get from the number variable. Is this helping?
18th Jan 2017, 11:58 PM
Marcellino Chris O'vara
Marcellino Chris O'vara - avatar
0
So "total" will be the sum of all inputs, not the number of inputs requested. I hope you can understand.
19th Jan 2017, 7:34 AM
Marcellino Chris O'vara
Marcellino Chris O'vara - avatar
0
while loop runs two times and total is required value of number every time because cin command is used in the while loop. because total=total+number
1st Feb 2017, 2:44 PM
mansi trivedi
mansi trivedi - avatar