public class ForLoopDemo {
/* In addition to the while and do-while loops.
* The Java language also provides the for loop.
* This is used to iterate through a range of values.
*/
public static void main(String[] args) {
// Count to 5 with a basic for loop.
for (int A = 0; A <= 5; A++){
System.out.println("A = " + A);
}
/* So the code above executes for as long as the
* value of A is less than or equal to 5.
*
* The next example will work it's way through
* an array. This is called an enhanced for loop.
*/
int[] B = {6,7,8,9,10};
for (int item : B) {
System.out.println("B = " + item);
}
// We can also do the same for strings.
String[] months = {"January","February","March","April","May","June",
"July","August","September","October","November","December"};
for (String item : months) {
System.out.println("The month is " + item);
}
}
}
No comments:
Post a Comment