How can I understand the while, do...while and increment operators in following program?

61 views Asked by At

I am here from a competitive exam on "c". I cant able find the answer for the following c program :

    int i=1;
    do
      while(i++>5);
    while(i++>4);
    while(i++>3);

The question is to find the final value of "i". I have find out that the output is "4" by using gcc. But, I can't understand the mechanism. Please explain me...

2

There are 2 answers

0
brokenfoot On BEST ANSWER

1st conditions

while(i++>5);

here i =1, it fails but increments it to 2.

2nd condition

while(i++>4);

again fails but increments i to 3

3rd conditions

while(i++>3);

again fails but increments i to 4

So, you end up with a 4

0
ciphermagi On

The tests increment. The loop executes and enters the text, while(i++>5); evaluates false, but i becomes 2. while(i++>4); evaluates false, but i becomes 3. while(i++>3); evaluates false (because of post-incrementing), but i becomes 4.