I can't understand that how it is giving me output 20 | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

I can't understand that how it is giving me output 20

9th Dec 2017, 1:21 PM
utkarsh
6 Answers
+ 3
may be it is taking some garbage value as you need to input 5 numbers
9th Dec 2017, 1:34 PM
Mansi Dagla
Mansi Dagla - avatar
+ 2
IF YOU ENTER 4, 5 TIMES While is a loop, that means it repeats some code until a condition is satisfied. Here, your condition is num<=5, For 1st iteration, num = 1,you input 4, which means number = 4. And total = total + number, which means, total = 0 + 4 = 4. Also num is incremented to 2. For 3nd iteration, num = 2,total = total(which is 4) + number(which is 4) = 8. And num is incremented to 3. next, num = 3, total = 8 + 4, num = 4. Next, num = 4, total = 12 + 4, num = 5 Finally, num = 5, total = 16 + 4 = 20, num = 6. Now this num is not <=5, so loop breaks and prints total, which is 20.
9th Dec 2017, 1:34 PM
Meharban Singh
Meharban Singh - avatar
+ 1
int num = 1; int number; int total = 0; while (num <= 5) { cin >> number; total += number; num++; } cout << total << endl;
9th Dec 2017, 1:25 PM
utkarsh
+ 1
and I have enter no. 4 when it ask to put a no.
9th Dec 2017, 1:27 PM
utkarsh
0
Code?
9th Dec 2017, 1:22 PM
Meharban Singh
Meharban Singh - avatar
0
thanks
9th Dec 2017, 2:24 PM
utkarsh