#Convert a do while loop to a for loop

14 messages · Page 1 of 1 (latest)

woeful stag
#

Question:

int x = 1, i = 2;
        do {
            x *= i;
        } while (++i <= 5);
System.out.println(x);

What I have done so far:

int x = 1, i = 2;
        for (i = 2; ++i <= 5;) {
            x *= i;
        }
System.out.println(x);

The output is supposed to be 120 but I'm getting 60 with what I've done.
Thank you in advanced!

simple bridgeBOT
#

This post has been reserved for your question.

Hey @woeful stag! Please use /close or the Close Post button above when you're finished. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.

TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.

fickle lance
#
int x = 1, i = 2;
while (i <= 5) {
    x *= i;
    i++;
}
System.out.println(x);  // 120
#
int x = 1, i = 2;
do {
    x *= i;
    i++;
} while (i <= 5);
System.out.println(x);  // 120
woeful stag
#

Really sorry for such a dumb question

fickle lance
#

there are no dumb questions

woeful stag
#

:)

#

Thanks

#

It work

fickle lance
#

no problem

woeful stag
#

That's why the ++i looked weird at first