Why the while loop is working correctly even if the ... | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Why the while loop is working correctly even if the ...

while (num < 6) { cout << "Number: " << num << endl; num = num + 1; } Here you can see num=num+1 is defined after cout but still the program is working correctly. C++ operates each and every statement line-wise then why it is showing the correct output.

25th Oct 2019, 3:00 AM
Amresh
Amresh - avatar
2 Answers
+ 6
The "correct" output depends on what you want. Incrementing num before cout will cause the incremented value to be printed instead of the value before being incremented. There is a difference between doing while (num < 6) { cout << num; num = num+1; } and while (num < 6) { num = num+1; cout << num; } Given that num is initialized as 0, the former prints 012345, while the latter prints 123456.
25th Oct 2019, 3:06 AM
Hatsy Rei
Hatsy Rei - avatar
+ 2
Ok ok I think the c++ manipulates while loop in such a way that it first check the condition If it is not satisfied then it moves inside and print whatever is given and after printing it, C++ again checks that if the condition is satisfied or not... That's why the num=num+1 is given at the last, which in first case don't show any change but when while loop prints second time then num= num +1 comes in light....
25th Oct 2019, 3:10 AM
Amresh
Amresh - avatar