+ 2

I don't get how num helps us find the find sum of user inputted numbers. please explain this code. Although I did notice that without it the output is always 0 no matter which number is inputted.

#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; }

9th Aug 2016, 6:15 AM
Sundus Yawar
Sundus Yawar - avatar
2 Réponses
+ 1
While num is able to be increased because it is defined as 1 in the condition 1 <= 5 ( 1,2,3,4,5) if user inputs 2 it is doing total(0) + number(2) * 5 = total = 10 For 3 total(0) + number(3) * 5 = total = 15 If num is not defined it has no number to use in the condition num <= 5.
9th Aug 2016, 7:32 AM
Jaque
Jaque - avatar
+ 1
Each time the statement loops, num is increased by one until num is greater than 5(as stated in the condition: while num is less or equal to 5). Which means the statement will loop 5 times and will add 1 to num every loop (num++ means num + 1) until the condition is not True anymore which is when num is greater than 5.
10th Aug 2016, 3:41 PM
Alexander Paul Mariñas
Alexander Paul Mariñas - avatar