+ 1

Explain this code please.

Well, i just want to know what's the difference between num and number here. Even tho i increase the value in the while loop more than five the code works in the same logic without giving an error please explain. #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 Dec 2017, 1:49 PM
Micro Pixels
Micro Pixels - avatar
7 Réponses
+ 2
(just in my answer, when taping, I commit an error, I write "number" is used to fix the number of iterations instead of 《"num" is used to fix the number of iterations 》) I think you get the idea and wish you the best of luck
16th Dec 2017, 3:54 PM
medidou
medidou - avatar
+ 7
'num' is used as a counter for a while loop and 'number' is input from the user and total is the addition of all the five inputs..
15th Dec 2017, 2:11 PM
Aaditya Deshpande
Aaditya Deshpande - avatar
+ 2
Aaditya is correct. In the while loop, you are using 'num' as the condition. When num is 5, the loop will go through one more time, because num is still equal to 5. At the end of the last loop, num is still incremented to 6. THEN the loop breaks.
15th Dec 2017, 4:05 PM
Zeke Williams
Zeke Williams - avatar
+ 2
it is a simple code number is used to fix the number of iterations (5 iterations ) in every iteration of the loop you check if num is <= 5 if yes we execute the instructions of the loop if not we will skip the loop and print the total's value for the loop you begin by giving a value to number after you increment total by adding number's value if you find that difficult I suggest you to return to C++ or algorithm courses. a few time is sufficient to understand all these stuffs
16th Dec 2017, 11:42 AM
medidou
medidou - avatar
+ 1
I thought Aaditya and I explained it sufficiently. There really is nothing left to say about it.
16th Dec 2017, 6:02 AM
Zeke Williams
Zeke Williams - avatar
+ 1
@medok Thanks!
16th Dec 2017, 2:48 PM
Micro Pixels
Micro Pixels - avatar
0
Anyone with better explanation?
16th Dec 2017, 5:48 AM
Micro Pixels
Micro Pixels - avatar