Java Reference
In-Depth Information
3. At the end of the for loop, i is incremented to i ++ or i =1 .
4. Return to the start of the for loop. i =1 and 1 < 12, so the loop is entered a second time.
5. i = i *2 or i = 1*2 = 2, so the statements are evaluated on the 2 (third) element of each
array.
6. At the end of the for loop, i is incremented to i ++ or i =3 .
7. Return to the start of the loop. i =3 and 3 < 12, so the loop is entered a third time.
8. i = i *2 or i = 3*2 = 6, so the statements are evaluated on the 6 (seventh) element of each
array.
9. At the end of the for loop, i is incremented to i ++ or i =7 .
10. Return to the start of the loop. i =7 and 7 < 12, so the loop is entered a fourth time.
11. i = i *2 or i = 7*2 = 14, so the statements should be evaluated on the 14 (fifteenth) element of
each array. However, there are only twelve elements in each array. Here you will run into an
error and the program will be terminated.
In short, a for loop is a control structure that lets you repeat a certain block of code a specified
number of times. The amount of times can be determined in advance or dynamically, depending on
the situation. When creating a for loop, pay attention to the initialization, termination, and incre-
ment specified to be sure you are not creating infinite loops or errors at execution.
Your First for Loop
try it out
 To create a simple for loop, follow these steps:
1. Create a new project in Eclipse. Perhaps call it Chapter5 to keep the exercises organized according
to the chapters in this topic.
2. Create a new class by right-clicking on the src folder in your new project. Select New and then
Class.
3. In the Name field, enter the name of your class, ForLoop , beginning with a capital letter by
Java convention. In the bottom portion of the New Java Class window, there is a section
that reads: “Which method stubs would you like to create?” You may choose to check the
box next to “ public static void main(String[] args) ” to automatically create a main
method.
4. You should automatically have the basis for the class body shown here:
public class ForLoop {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
Search WWH ::




Custom Search