Loops (aka "iterations")

In Java we have 3 basic loop statements:

Pseudocode:
Mom says you have to eat all your peas before you get dessert.

//while loop while (peas are still on the plate) eat peas; //do..while loop do eat peas; while (peas are still on the plate); //for loop, 3 more big bites! for(3 bites) eat peas; ////////////////////////////////// public static void main(String args []) { int x=0; //counter variable do { x=x+2; //increment x System.out.println(x); } while (x<10); } /////////////////////////////////// public static void main(String args []) { int x=0;//counter variable while (x!=10)//conditional expression { x=x+2; //increment x System.out.println(x); }//compound statement } ///////////////////////////////////// public static void main(String args []) { //counter is the "for loop control variable" and starts at 1 //counter<=3 is the condition under which the loop continues //counter++ is done at the end of each iteration for (int counter=1;counter<=3;counter++) System.out.println("GMU totally rules!"); } Note that in the example above, only one statement belongs to the loop. If you wish to repeat more than one statement, the statements must be bounded by brackets { }. This is called making a compound statement.

Click here to return


Copyright © 1999-2002 All Rights Reserved