2

Ages since I have written a do while.

Whats wrong with this do while

int i = 0;
    do { 
        System.out.println(i);
    } while(++i == 500);

I only goes once through the loop, and IMO it should iterate 500 times.

11
  • 1
    it should be "equal to" 500 that many times?
    – FatalError
    May 31, 2012 at 13:05
  • 1
    How many times will i equal 500 if it starts at 0? A print statement or a debugger would have answered this immediately. May 31, 2012 at 13:06
  • 3
    Frack! Of course. I still don't understand the down votes. Its an honest blunder :/ May 31, 2012 at 13:09
  • 7
    Maybe I'm a little rude here but... your profile says Senior Java Developer.... hmmm.... PS: The downvotes are probably because you should've tried to figure it out on your own, not jump straight to stackoverflow. May 31, 2012 at 13:09
  • 1
    @SoboLAN Sometimes it's too obvious and you are not looking in the right place. Taking a step back or starting to ask the question is often enough. In some occasions, you might even go as far as validating the question. ;-)
    – assylias
    May 31, 2012 at 13:11

5 Answers 5

21

You probably meant

while (++i < 500);

instead of

while (++i == 500);
14

It is a do-while loop of Java, not the repeat-until loop of Pascal. Its expression specifies the continuation condition, not the exit condition.

do { 
    System.out.println(i);
} while(++i != 500);
1

It will only iterate once because of your condition. while (++i == 500) ++i will be 1 and never 500, so it evaluates to false and won't continue.

1
  • You are right, I should actually look at the numbers first. It won't be 2, but it will never be 500.
    – firelore
    May 31, 2012 at 13:44
0

In your code initially the value of i (i.e. 0) will be printed because it is a do while and the code inside the loop should be executed at least once.
And then now the condition will be checked. It will be checked that if ++i equals 500 (i.e 1==500) which returns false and hence the loop breaks.

while (++i < 500);

changing the condition to the above statement may cause the loop to continue untill the value of i becomes 500

0
while(++i != 500)
{
    System.out.println(i);
}

is the better way.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.