for LoopPurpose:
- To repeat a block of code a predetermined number of times.
Mechanics:
for (<counter initialization>; <loop continuation condition>; <counter increment>) {/* Java statements */
}
Example:
for (int i=0; i<10; i++) {/* Java statements */
}
Usage:
- <counter initialization> is a variable of an
ordinal type, such as an
integerinitialized to a value. - The <loop continuation condition> determines how long the program will continue to loop.
- <counter increment> increments the counter using
an increment operator, usually
<counter>++. - The
/* Java statements */can be any legal Java statements. If more than one statement is to be repeated, then curly brackets must surround the repeated code. Otherwise, the curly brackets are optional.
Restrictions:
- When the
forstructure begins executing, the counter is initialized. Then, the <loop continuation condition> is checked. If the condition is satisfied, the/* Java statements */are executed, and then the counter is incremented. The loop begins again by checking the <loop continuation condition>. This process continues until the control variable no longer satisfies the <loop continuation condition>. The program continues by performing the first statement after theforstructure. - The value of <counter> can be used in a expression but cannot be changed with an assignment statement in the body of the loop.
email suggestions to: cs015tas@cs.brown.edu
