• Steam recently changed the default privacy settings for all users. This may impact tracking. Ensure your profile has the correct settings by following the guide on our forums.

For loops

karnbmx

ceebs. :)
Hello,

I am currently learning Java. While studying loops, I came across FOR loops. The wording from the official Java website I was learning from was a little ambiguous, so I couldn't completely understand it.

So is there any simpler way to understand Java FOR loops? If so, help would be really appreciated.
 

Chathurga

Active Member
[highlight=java]for (int i = 0; i < 5; i++) {
System.out.println("i equals: " + i);
}[/highlight]

That will print out:
Code:
i equals: 0
i equals: 1
i equals: 2
i equals: 3
i equals: 4

If you need more explanation just post what you don't understand.
 

NoEffex

Seth's On A Boat.
To go further in-depth,

[highlight=java]for (int i = 0/*Set a variable, you can use a pre-existing one, or nothing*/; i < 5/*The statement that acts much like a while loop*/; i++/*This is executed after each loop.*/) {
System.out.println("i equals: " + i);
}[/highlight]

So, it would be the equivalent of

[highlight=java]int i = 0;
while(i < 5) {
System.out.println("i equals: " + i);
i++;
}[/highlight]
 

karnbmx

ceebs. :)
Cool! Both explanations clear it up a lot. Thanks!
 

A_Nub

Developer
Also remember the declaration of int i in a for loop is local to that for loop so technically the equivalent is
Code:
{
    int i = 0;
    while(i < 5) {
	    System.out.println("i equals: " + i);
            i++;
    }
}

The extra brackets create a so called "section" where anything declared inside is local to that section only. At least thats how it is in C and C++, I would believe java has this functionality too.

Also mind that the above are extremely simplistic samples, just remember for(declaration; conditional; postop) and then you should be set ;)
 
Top