for loop




A for loop is a control structure that allows you to repeat a series of instructions over and over again. The for loop is a pre-test loop, since the boolean expression is evaluated before the loop body (i.e. the loop may be skipped). Loops are especially useful to traverse (travel across) an array or an ArrayList (or similar data structure).

Example:


// The following code prints out 0 1 2 3 4 done
// Here are the steps executed: 
// Step 1: int i=0;  creates a variable called i and sets 
//                          the value to 0 (happens once)
// Step 2: i<5; is evaluated and if true, the instruction 
//                        System.out.print(i+" "); is executed
//                     if false, exit (terminate) the loop, 
//                        and continue with the 
//                        next instruction after the loop body
// Step 3: Execute the instructions in the body of the loop
//             System.out.print(i+" ");
// Step 4: i++ is executed at the end of the loop
// Step 5: Go to step 2.
 

for (int i=0; i<5; i++)
    System.out.print(i+" ");
System.out.print("done");	
	

// the for loop header has 3 sections
// Section 1:  int i=0;  Initialization (happens first but only once)
// Section 2:  i<5;      Conditional (boolean expression)
// Section 3:  i++       Finalization (what to do at the end of the loop)


More Examples:

// prints HelloHelloHello for (int i=0; i<3; i++) System.out.print("Hello");
// prints HelloHelloHello for (int i=1; i<=3; i++) System.out.print("Hello");
// note that 2 instructions are executed each time through the loop // the braces { } are used to block off the body of the loop // prints HelloByeHelloByeHelloBye for (int i=1; i<=3; i++) { System.out.print("Hello"); System.out.print("Bye"); }
// prints Hello Bye Hello Bye Hello Bye for (int i=1; i<=3; i++) { System.out.println("Hello"); System.out.println("Bye"); }
// prints HelloBye HelloBye HelloBye for (int i=1; i<=3; i++) { System.out.print("Hello"); System.out.println("Bye"); }
// prints 1 10 2 20 3 30 for (int i=1; i<=3; i++) System.out.println(i + " " + i*10);
// prints 1 10 2 20 3 30 for (int i=1; i<=3; ) { System.out.println(i + " " + i*10); i++; } Note that the finalization segment may be skipped, however this approach is not recommended.
// prints 0 10 1 20 2 30 int [] myList = {10, 20, 30}; for (int i=0; i<myList.length; i++) System.out.println(i + " " + myList[i]);
// prints 0 10 1 20 2 30 ArrayList myList = new ArrayList(); myList.add(10); myList.add(20); myList.add(30); for (int i=0; i<myList.size(); i++) System.out.println(i + " " + myList.get(i));