“For” loop examples

A few for loop examples:

    • General form: 

for (init; condition; step) {
statements
}

  • init done once at start of the loop
  • condition (can be a boolean) checked before every iteration through the loop – we execute the statements if they are true.
  • step every time through loop after statements
  • example:

for (int i = 0; i < 5; i++) { println(i); }

The result here of course would be the counting up to 5, starting at 0, and the output would be 0, 1, 2, 3, 4

  • Another example of counting down:

for (int i = 6; i > 0; i -= 2) {

println(i);

}

This will cause 2 to be subtracted from i with each pass through the loop and will not print out 0 because 0 is not > 0:

6

4

2

Here is an enhanced "for" loop in Java introduced in Java 5:

public class Test {

public static void main(String args[]){
int [] numbers = {10, 20, 30, 40, 50};

for(int x : numbers ){
System.out.print( x );
System.out.print(",");
}
System.out.print("n");
String [] names ={"James", "Larry", "Tom", "Lacy"};
for (String name: names) {
System.out.print(name);
System.out.print(",");
}
}
}

Here your output will look like:
10,20,30,40,50,
James,Larry,Tom,Lacy

The "break" keyword will end the loop if a condition is met, for example:

for(int x : numbers ) {
if( x == 30 ) {
break;
}

As such the following output:
10,20

The continue keyword will continue the loop and for example, skipping thirty something like this:

if( x == 30 ) {
continue;
}

and the following output:
10,20,40,50

kudos to Stanford University & http://www.tutorialspoint.com/