increments

Hi this is very basic stuff but I have no idea how this code works systemically. I am supposed to determine the outputs respectively.
1
2
3
4
5
6
7
int main () {
int i = 5;
cout << 5 / 2 << endl;
cout << 5.0 / 2 << endl;
cout << i++ << endl;
cout << ++i << endl;
}


Could someone please explain it step by step for each line? How did 5 and 7 get printed out for the 3rd and 4th output?

Thanks
Last edited on
Line 5: This is a post increment. This means the value is used before it is incremented. The value of i before line 5 is 5, which is what gets printed. i is then incremented and becomes 6.

Line 6: This is a pre-increment. This means i is incremented before being used. I is currently 6, is incremented to become 7, then printed.
1
2
cout << i++ << endl;
cout << ++i << endl;


The first one: "i" is printed before "i" is incremented. So it prints 5 and that does 5 + 1.

The second one: "i" is incremented before "i" is printed. So it does 6 + 1 and then prints 7.
Topic archived. No new replies allowed.