The general form of for loop consists of three parts:
-----------------------------------------------------
for (initialization; termination; increment) {
....
}
-----------------------------------------------------
The initialization: it initializes the loop, it executed once at the beginning of the loop.
The termination: the loop executes as long as the termination evaluates to true.
The increment: it executed at the end of every loop, the expression can be either an increment or decrement.
package org.kodejava.example.lang; public class ForDemo { public static void main(String[] args) { // // Do a loop from 0 to 10. // for (int i = 0; i <= 10; i++) { System.out.println("i = " + i); } // // Loop through all the array items. // int[] numbers = new int[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; for (int number : numbers) { System.out.println("number = " + number); } } }The result of the program is:
i = 0
i = 1
i = 2
i = 3
i = 4
i = 5
i = 6
i = 7
i = 8
i = 9
i = 10
number = 0
number = 1
number = 2
number = 3
number = 4
number = 5
number = 6
number = 7
number = 8
number = 9
number = 10
Aucun commentaire:
Enregistrer un commentaire