The For-Loop

Things To Do First

Things To Do Later

Counted Loops (For Loop)

A lot of loops, like the ones we've already worked with, are counted loops. This means that they have a definite number of iterations. In our first example, we counted until we reached the value specified by the user. We knew there would be a definite number of iterations. In our second example, our number of iterations depended on how many times it would take the user to enter a valid number. In this case, there is an indefinite or undetermined number of iterations because we don't know how many tries the user would need. The same would apply if you were using a loop to process a file - you can never know how many records are in a file at any given time, so you can't determine the number of iterations of a loop that processes a file.

We often use while-loops or do-loops to perform an indefinite loop, or a loop where we can't determine the number of iterations. When we do know that there will always be a definite number of iterations, such as a loop that counts until it reaches a specific value, we can use a special counted loop. In Java, and a number of other programming languages, this is called a for-loop. The syntax for a for-loop can be found in chapter 5.7 of your text, and the flowcharts in Figure 5.3 in chapter 5.7 show how a for-loop works.

The for-loop performs some of the tasks that you have to code for yourself in a while-loop or a do-loop. These include:

  1. initialization of the counter variable
  2. evaluation of a condition
  3. incrementing, or other expression that keeps the loop going

Using our counting example discussed in the beginning of this session, we can determine that our loop starts at 1, continues until it reaches the user-specified value, and increments by 1. In a for-loop in Java, this would be written as:

public class ForLoopExample {

    public static void main(String[] args) {

        Scanner in = new Scanner();
        System.out.println("Enter a value to count to:");
        int number = in.nextInt();

        for (int counter=1; counter <= number; counter++) {
            System.out.println(counter);
        }
    }
}

In this loop, the three tasks are specified inside the brackets and separated by semicolons:

If you type this code into a Java program, you'll see that it executes exactly the same way as the first While example! The difference is that the For-Loop is made up of fewer statements.

As with other loops, if you have more than one statement inside the body of the loop, you must have braces surrounding the statements to be repeated.

Exercises

How would you make the for-loop in the previous example count backwards? Do it!

[solutions]

1. What's the output of the following code segments:

a.

int i;
for (i=0; i<5; i++)
{
	System.out.print(i + ", ");
}
System.out.println("\nAfter the loop, i is " + i);

b. >

for (int i=0; i<=20; i+=4) {
   System.out.print(i + " ");
}

c.

for (int i=1; i<=21; i+=3) {
   System.out.print(i + " ");
}

d.

for (int i=20; i>=0; i-=4) {
   System.out.print(i + " ");
}

2. Write a program that converts Fahrenheit to Celsius temperatures. The starting value and ending value of Fahrenheit temperatures to convert are to be retrieved from the user. Celsius = (5.0 / 9.0) * (Fahrenheit - 32). Use a for-loop.

3. Investment Problem: Have the user input an investment amount and an interest rate. Have the program use a for-loop to output a list showing the value of the investment at the end of each year for 5 years. For example:

Enter the investment amount: 1000
Enter the interest rate: 10
After year 1: $1100.00
After year 2: $1210.00
After year 3: $1331.00
After year 4: $1464.10
After year 5: $1610.51

For more practice, try questions 5.2, 5.4, and 5.6 at the end of Chapter 5.