Page 492 - Introduction to Programming with Java: A Problem Solving Approach
P. 492
458
Chapter 11 Type Details and Alternate Coding Mechanisms
System.out.print("Enter countdown starting number: ");
count = stdIn.nextInt();
for (; count>0; count--)
}
System.out.println("Liftoff!");
no initialization component
{
System.out.print(count + " ");
Actually, it’s legal to omit any of the three for loop header components, as long as the two semicolons still appear within the parentheses. For example, you can even write a for loop header like this:
for (;;)
When a for loop header’s condition component (the second component) is omitted, the condition is consid- ered true for every iteration of the loop. With a permanently true condition, such a loop is often an infinite loop and a logic error. But that’s not always the case. You can terminate it by using a break statement like this:
for (;;)
{
}
}
...
if (<condition>) {
break;
}
You should understand the above example in case you see similar code in someone else’s program. But it’s rather cryptic, and, as such, you should avoid writing your own code that way.
Multiple Initialization and Update Components
For most for loops, one index variable is all that’s needed. But every now and then, two or more index vari- ables are needed. To accommodate that need, you can include a list of comma-separated initializations in a for loop header. The caveat for the initializations is that their index variables must be the same type. Work- ing in concert with the comma-separated initializations, you can also include a list of comma-separated updates in a for loop header. The following code fragment and associated output show what we’re talking about. In the for loop header, note the two index variables, up and down, and their comma-separated ini- tialization and update components.
System.out.printf("%3s%5s\n", "Up", "Down");
for (int up=1,down=5; up<=5; up++,down--)
{
Apago PDF Enhancer
System.out.printf("%3d%5d\n", up, down);