AP Computer Science Java: Lesson 3.1
Repetitive Statements - For Loops

Lesson 3.1 - For Loops

Purpose: To learn how to write and use a Java for loop

An important feature of computer programs is a loop - the ability to repeat a portion of code as many times as needed. Unlike humans, computers have no problem following the same set of instructions over and over. There are two main loops that we will learn to code repetition. The first loop falls under the definition of a definite or counted loop. It is used when we know precisely how many times we need the computer to do something. The name of this structure is the for loop. Here is its format:

   for(initialization; continuing condition; incrementation)

Here is an example :

   for(x=1; x<=10; x++)
      System.out.print((2*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:

for(c='A'; c<='Z'; c++) //count by one's from A to Z

In closing
, Remember that only integers and characters may be used as loop control variables. NO DOUBLES! Lastly, when the number of repetitions to performed is known, the for loop is the choice for the task.

© DanShuster.com