+ 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??
6 Answers
+ 3
yes.. much appreciated bro
+ 2
So is "total" the total num of inputs or the sum of all the inputs?
+ 1
but when i run it it's giving total=2... can anyone please explain....
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?
0
So "total" will be the sum of all inputs, not the number of inputs requested. I hope you can understand.
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