1. for (<start value>; <condition>; <increment>){
  2. // code block
  3. }
  1. for(int counter=0; counter < 5; counter = counter + 1){
  2. System.out.println("Hello");
  3. }

The above code will print out "hello" 5 times. The start value is 0 and the counter variable is called counter. In a loop we need to keep track of how many times the loop has err looped! This is so we can stop it! This is called the counter and it is nessesary to allow the condition to be satisfied. If the condition is NEVER satisfied then you get what is called a infinite loop. This will NEVER stop. For example -

for(int a=0; a<10; b = b + 1){

System.out.println("SPAMMMM!!!");

}

The above code will never stop. The reason for this is that "a" will never be above 10. The increment code, which gets run at the end of the code block, adds 1 to the varaible "b". As the condition is testing "a" we get an infinite loop.

  1. int a= 0;
  2. for(System.out.println("Start me"); a<4; System.out.println("Inc me " + a)){
  3. System.out.println("hello");
  4. a = a + 1;
  5. }

The above code shows a Java quirk in that we can put ANY code in the start and incrment positions. You can be ever so clever about this if you want but it does show something very interesting. Look at the output of this code (yes it does compile and stop!).

Start me
hello
Inc me 1
hello
Inc me 2
hello
Inc me 3
hello
Inc me 4

Did you expect that? This is a great way of seeing the order of the for loop. So we do -

  1. Run start value code
  2. Test the condition if true continue otherwise stop
  3. run code block
  4. run increment code
  5. jump back to 2

Notice that the increment happens AFTER the code block. The condition is run BEFORE the code block and we ALWAYS test the condition after the code block REGARDLESS.

next for loops and arrays >>

 
Basics
Menu
Search