# cout << (--i)-- << " "; and the answer is?

Discussion in 'Programmer's Corner' started by summeranson, Sep 24, 2009.

1. ### summeranson Thread Starter Member

Feb 12, 2009
28
0
If i = 5, what will be the result of:

do
{
cout << (--i)-- << " ";
} while(i>=2 && i < 5);

A. It won't enter the loop

B. It will loop forever

C. I don't know

D. Compiler error

E. 4 3 2 1

F. 4 3 2

G. 4 2 1

H. 4 2

2. ### mik3 Senior Member

Feb 4, 2008
4,846
63

What do you think?

What you don't know?

3. ### summeranson Thread Starter Member

Feb 12, 2009
28
0
i think the answer is H issit? i am not sure about the -- behind the (--i)--

4. ### mik3 Senior Member

Feb 4, 2008
4,846
63
I think the answer is A because i=5 and it will never enter the loop.

Another possible answer is D because of (--i)-- but I think it is possible to use both --i and i-- in C but with a slightly different functionality.

5. ### odinhg Active Member

Jul 22, 2009
65
15

i = 5;
do{
cout << (--i)-- << " ";
} while(i>=2 && i < 5);

First it will enter the loop before checking that i>=2 and i<5 because it's a do-while loop.

Then it will decrease i by 1 and print it (i-1 = 4), then decrease it by 1 another time.

Now i is 3 and i>=2&&i<5 is true, so it will run the loop again.

Decrease i with 1, which gives us 2 and print it, then decrease it with 1 another time.

Now i is 1, so i>=2&&i<5 is false and the loop stops.