+ 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
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
+ 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++ đ€
+ 2
1: x += x++ //x = 3
2: x += x++ //x = 7
3: x += x++ //x = 15
4: x += x++ //x = 31
0
Its c++