Hello

Ive come up with a stupid question that just needs a why

What would this do?

for (int i=5; i<2;i++)
{
System.out.println("What?");
}
System.out.println("Who?");

Print "Who?" once? I can't see it looping because i will never be < 2 when it starts at 5. That being said, the only print should be "Who?".

Edited 3 Years Ago by Stuugie

Print "Who?" once? I can't see it looping because i will never be < 2 when it starts at 5. That being said, the only print should be "Who?".

The problem is that it is a "if" before it is actually a "for"...

That "for" loop (according to what you have said) is the same as a while loop saying:
_

int i=5
while (i<2)
{
System.out.println("What?");
}
System.out.println("Who?");

Edited 3 Years Ago by riahc3

I just ran your code and it indeed printed who? once and that was it. I don't really get what you mean by:

The problem is that it is a "if" before it is actually a "for"...

but the while loop seems like it will do the exact same as the for loop.

The basic for statement executes some initialization code, then executes an Expression, a Statement, and some update code repeatedly until the value of the Expression is false.

What is "some initialization code"? Because that happens before the second step which is making sure the expression is true before entering...

Someone will correct me if I'm wrong but the initialization code would be the code that is bold.

for (int i = 0;i<something.length;i++)

or in your case
for (int i=5;i<2;i++)

Edited 3 Years Ago by Stuugie

That "for" loop (according to what you have said) is the same as a while loop saying:

Close. It's more like this (note that the braces introducing a scope are significant):

{
    int i = 5;

    while (i < 2)
    {
        System.out.println("What?");
        i++;
    }
}

System.out.println("Who?");

Since i is never less than 2, the loop body is never entered, and the only output is "Who?".

This article has been dead for over six months. Start a new discussion instead.