0

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?");
4
Contributors
7
Replies
45
Views
3 Years
Discussion Span
Last Post by deceptikon
Featured Replies
  • See the Java Language Spec 14.14 - it makes this very clear... http://docs.oracle.com/javase/specs/jls/se5.0/html/statements.html#14.14 Read More

  • 2

    > 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 … Read More

1

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 by Stuugie

0

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 by riahc3

0

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.

0

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...

0

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 by Stuugie

2

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 topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.