Class 1, Part 2 |
Intro to Java 30-IT-396 |
|
For Loop
-
If you know ahead of time, or can calculate ahead of time, how many iterations
the loop will execute, it is often best to use a for loop.
-
The for loop takes three arguments: the initialization, the condition,
and the increment.
-
Initialization is often used to initialize a counter variable.
-
The condition is often used to compare that counter variable to another
value. When this condition is true, the loop executes for another
iteration. When false, it exits.
-
The increment often changes the value of the counter variable. Usually,
it increments it by 1, but you can certainly change it by another value
if you wish.
-
Since you know the size of an array ahead of time, the for loop is often
used to iterate through arrays.
for (int i = 0; i < array.length; i++) {
System.out.println(array[i]);
}
-
Imagine sending a message to five computers. The IP addrsses of these
computers can be held in an array. Then, you can use a for loop to
iterate through each IP address and send an appropriate message.
Infinite Loops, Break, Continue


Created by: Brandan
Jones January 4, 2002