Please, help me out explaining the code

I know it might be too easy for some of you but I came across this simple code and I don't know why the answer is that. Would you please explain where I am mistaken line by line.

1
2
3
4
5
int x=3; 
    while (x++<10) {   // 1) x=3,(after it comes down to x++), then x=5 
        x+=2;          // 2) x=6 (after x++), then x=8
    }                  // 3) x=9 (after x++). then x=11
    cout <<x;


The right answer is 13 and I can't figure out why. Your help is much appreciated. Thanks in advance.
x = 3

x++ ---> x incremented to 4, but previous result (3) compared to 10
x += 2 ---> x incremented to 6

x++ ---> x incremented to 7, but previous result (6) compared to 10
x += 2 ---> x incremented to 9

x++ ---> x incremented to 10, but previous result (9) compared to 10
x += 2 ---> x incremented to 12

x++ ---> x incremented to 13, but previous result (12) compare to 10
12 > 10, break

final result is 13.

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>

int main()
{
    using std::cout; 

    int x=3; 
    while (x++<10) { 
        x+=2;       
    }                
    cout <<x;
}
Last edited on
this is just interview/test type question that is intentionally hard to follow.
x is 3.
is x<10? x is incremented to 4.
it was < 10.
add 2, x is 6.
is x < 10? add 1
x is 7.
add 2, x is 9.
is x < 10, add 1
x is 10.
add 2, x is 12
is x < 10? it isnt, add one. //the ++ happens whether the condition is true or false!!! this is likely what you missed.
x is 13.


Last edited on
Thanks, that's clear now! It was really tricky and I didn't know that the last time we increment it ++(when the condition is wrong), it adds 1 even then and makes it 13.
Last edited on
Topic archived. No new replies allowed.