Overview of This Lesson

A lot of loops, like the while-loop and do-while loop we've already worked with, are counted loops. This means that they have a definite number of iterations; for example, if you have a counter variable that is initialized to 1, and your loop condition is counter <= 5, then your loop will execute 5 times. In this case, we know there are a definite number of iterations.

In one of our other examples, the number of iterations depended on how many tries 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 execute code an indeterminate number of times, where the number of iterations will depend on other factors than just counters. 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.

Pre-Requisites

Before doing this lesson, make sure you've completed the While Loops tutorial.

The For Loop

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

The general syntax of a for loop is:

for (initialization; condition; increment) {
    // loop body
}

Using our counting example discussed in the while loops lesson, 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-Loop example. The difference is that the For-Loop is made up of fewer lines of code.

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. But if you have only one statement in the for-loop body, you can omit the braces:

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

How would you make the for-loop in the example count backwards? We would have to make the following changes:

Try it!

for (int counter=number; counter >= 1; counter--) {
    System.out.println(counter);
}

Exercises

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

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

a.

0, 1, 2, 3, 4, 
After the loop, i is 5

b.

0 4 8 12 16 20

c.

1 4 7 10 13 16 19

d.

20 16 12 8 4 0

Question 2:

solution to question 2
Question 2. fahrenheit/celcius conversion table

Question 3:

solution to question 3
Question 3. investment value