AP Computer Science Java: Lesson 3.1 Repetitive Statements  For Loops 

for(initialization; continuing condition; incrementation) Here is an example : for(x=1; x<=10; x++) This statement says to begin the counter x at 1, continue with the loop as long as x is less than or equal to 10 and count by 1 (x++). For each value of x, the computer is instructed to display 2 times x. So we will see 2 4 6 8 ... 20 on the screen when this code executes. Let's take a look at each part of the for statement: Ininitialization The statement "x=1" in the for loop inititalizes the counter x, or gives it a beginning value. Most loops will begin at one, but not always. It depends on the needs of the program. Inititialize the counter to the value that makes sense. One note: the loop control variable (in this case, x) must be an integer. Condition The middle part of the for statement is what determines the end of the loop. As long as the condition is met, the loop continues. When it is not met, the loop terminates and program flow continues on the next statement after the for loop. In the example given earlier, the incrementation of x will eventally cause it to be 11. That value is not less than or equal to 10, so the loop stops. Incrementation The statement x++ is shorthand notation for "add 1 to x". There are two other ways to write this statement: x = x + 1 or x+=1. Counting by one is most common in for loops, but there are situations requiring counting by other numbers, or even counting backwards. Here are some examples: for(x=2; x<=20; x+=2) //count by two's from 2 to 20 for(x=0; x<=100; x+=5) //count by fives's from 0 to 100 for(x=5; x>=1; x) //count backward by one's from 5 to 1 Characters It is also possible to use a character variable as loop counter. Example:


© DanShuster.com