|
|
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
The forstatement provides a compact way to iterate over a range of values. The general form of the
forstatement can be expressed like this:initialization is a statement that initializes the loop--it's executed once at the beginning of the loop. termination is an expression that determines when to terminate the loop. This expression is evaluated at the top of each iteration of the loop. When the expression evaluates tofor (initialization; termination; increment) { statement }false, the loop terminates. Finally, increment is an expression that gets invoked for each iteration through the loop. Any (or all) of these components can be empty statements.Often
forloops are used to iterate over the elements in an array, or the characters in a string. The sample shown below,ForDemo, uses a
forstatement to iterate over the elements of an array and print them:The output of the program is:public class ForDemo { public static void main(String[] args) { int[] arrayOfInts = { 32, 87, 3, 589, 12, 1076, 2000, 8, 622, 127 }; for (int i = 0; i < arrayOfInts.length; i++) { System.out.print(arrayOfInts[i] + " "); } System.out.println(); } }32 87 3 589 12 1076 2000 8 622 127.Notice that you can declare a local variable within the initialization expression of a
forloop. The scope of this variable extends from its declaration to the end of the block governed by theforstatement so it can be used in the termination and increment expressions as well. If the variable that controls aforloop is not needed outside of the loop, it's best to declare the variable in the initialization expression. The namesi,j, andkare often used to controlforloops; declaring them within theforloop initialization expression limits their life-span and reduces errors.
|
|
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |