Shervin Asgari
Shervin Asgari

Reputation: 24499

do while syntax for java

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.

Upvotes: 2

Views: 27634

Answers (5)

rb2750
rb2750

Reputation: 1

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

is the better way.

Upvotes: 0

Subi
Subi

Reputation: 23

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

Upvotes: 0

firelore
firelore

Reputation: 518

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.

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726499

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);

Upvotes: 14

Jesper
Jesper

Reputation: 206786

You probably meant

while (++i < 500);

instead of

while (++i == 500);

Upvotes: 21

Related Questions