While loop | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

While loop

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

21st Jun 2019, 3:37 PM
Awaji Charles
4 Answers
+ 9
Your 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
21st Jun 2019, 5:10 PM
Prince PS[Not_Active]
Prince PS[Not_Active] - avatar
+ 5
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++ 🤓
21st Jun 2019, 3:55 PM
Anna
Anna - avatar
+ 2
1: x += x++ //x = 3 2: x += x++ //x = 7 3: x += x++ //x = 15 4: x += x++ //x = 31
21st Jun 2019, 4:56 PM
Seb TheS
Seb TheS - avatar
0
Its c++
21st Jun 2019, 3:59 PM
Awaji Charles