+ 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; }
13 odpowiedzi
+ 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.
+ 4
Thank you so much
+ 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
+ 2
So it's adding 6 five times ?? Because 6 is greater than 5??
+ 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.
+ 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.
- 1
Hii
- 1
Hii
- 4
Hi