I did this Int x = 1; While (x<=15) { Cout << "this is a loop" << endl; X+= x++; Then the loop ran only 4 times I want to know why
6/21/2019 3:37:28 PM
Awaji Charles4 Answers
New AnswerYour whole code is this : #include <iostream> using namespace std; int main() { int x = 1; while (x<=15) { cout<< "this is a loop" << endl; x+= x++; } return 0; } Here 1st run of loop : x+=x++ x++=2 so x+=2 Which is 3 Now x=3 2nd run of loop : x+=x++ 3+=4 Now x=7 3rd run x+=x++ 7+=8 That is 15 Now x=15 4th run : 15+=16 x=31 Which is greater than 15 Code Stops Thanks
Not sure about Java or other languages, but if this is C/C++, expressions like x += x++ lead to undefined behavior and must be avoided. /Edit: ok, cout. It is C++ π€
Sololearn Inc.
535 Mission Street, Suite 1591Send us a message