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.
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:
initialization of the counter variable
evaluation of a condition
incrementing, or other expression that keeps the loop going
The general syntax of a for loop is:
for (initialization; condition; increment) {
// loop body
}
initialization is the expression that
initializes (and usually also declares) the variable used
to control the loop, i.e. the loop counter
condition is the boolean expression that
determines the conditions that must be true for the loop to
continue; when the condition is false, the loop terminates
increment is the expression that modifies
the loop variable at the end of each iteration (e.g increment
or decrement the loop counter)
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:
initialization: int counter = 1;
counter is initialized to
a value of 1
we are also declaring the counter in this statement: this is
allowed, but only if the counter is not used outside the loop
since the counter is local to the loop block
condition evaluation: counter <= number;
this loop will continue as long as this condition is true
(as long as counter remains less than or equal
to the value of number)
when the condition is false (the counter
becomes greater than number), the loop
terminates
increment: counter++;
this statement increases the counter by 1
this increment takes place after the body of the
loop executes and before the condition is
evaluated again
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:
The loop counter is initialized to the number value,
because we want to start printing at the user-entered number
The loop condition should be "as long as the counter value is
1 or more: counter > 1
The increment expression should actually be changed
to a decrement expression: counter--
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);
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: