+ 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; }
7 Respostas
+ 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
+ 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..
+ 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.
+ 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
+ 1
I thought Aaditya and I explained it sufficiently. There really is nothing left to say about it.
+ 1
@medok Thanks!
0
Anyone with better explanation?