+ 5

I can't understand how the output of this code is 30..

#include <iostream> using namespace std; int main() { int num = 1; int number; int total = 0; while (num <= 5) { cin >> number; total += number; num++; } cout << total << endl; return 0; }

15th Sep 2019, 6:26 AM
Shrutika Singh
Shrutika Singh - avatar
13 Answers
+ 9
Explanation đŸ‘‡đŸ» 1<=5 Cin>>number (which is 6) Total=total+number =(0+6)=6 (increment 1) 2<=5 Total=total+number=(6+6)=12( increment 2) 3<=5 Total=total+number=(12+6)=18(increment 3) 4<=5 Total=total+number(18+6)=24(increment 4) 5<=5 Total=total+number(24+6)=30 (stop execution when condition false at num=6) and print 30.
16th Sep 2019, 5:58 AM
Ayushi Gujarati
Ayushi Gujarati - avatar
+ 4
Thank you so much
15th Sep 2019, 7:09 AM
Shrutika Singh
Shrutika Singh - avatar
+ 2
But how.? I put the input 6 but I don't understand how the output is 30.. I know it's basic but I am having trouble reading and understanding the code
15th Sep 2019, 6:55 AM
Shrutika Singh
Shrutika Singh - avatar
+ 2
So it's adding 6 five times ?? Because 6 is greater than 5??
15th Sep 2019, 7:02 AM
Shrutika Singh
Shrutika Singh - avatar
+ 2
Not because 6 is greater than 5. It's adding because you are giving 6 as input. If you 7 as input then output will be 35 because then it will add 7. When you enter the input, it will get stored in your variable "number" and the next line total += number is equivalent to total = total + number, that means each time it add number into total and value of total keep increasing.
15th Sep 2019, 7:06 AM
Vijay Meena
+ 1
As you can see loop will run 5 times for value of num = 1,2,3,4,5 after it will terminate. Since you are giving 6 as input for 5 times and adding them to total. So value of total will keep increasing by 6 each time loop execute. After 5 iterations of loop value of total =30, that's why output is 30.
15th Sep 2019, 7:01 AM
Vijay Meena
- 1
Hii
17th Sep 2019, 6:06 AM
Sachin Pandit Parjapti
Sachin Pandit Parjapti - avatar
- 1
Hii
17th Sep 2019, 6:06 AM
Sachin Pandit Parjapti
Sachin Pandit Parjapti - avatar
- 4
Hi
15th Sep 2019, 4:59 PM
shubham gholap