Java Reference
In-Depth Information
As discussed in the previous section, the most common error associated with loops is off by
one. If a loop turns out to be an infinite loop, the error is most likely in the logical
expression that controls the execution of the loop. Check the logical expression carefully
and see if you have reversed an inequality, an assignment statement symbol appears in place
oftheequalityoperator,or && appears in place of || . If the loop changes the values of
variables, you can print the values of the variables before and/or after each iteration or you
can use your IDE's debugger, if any, and watch the values of variables during each iteration.
The debugging sections in this topic are designed to help you understand the debugging
process. However, as you will realize, debugging can be a tiresome process. If your
program is very bad, do not debug, throw it away and start over.
Nested Control Structures
In this section, we give examples that illustrate how to use nested loops to achieve useful
results and process data.
5
EXAMPLE 5-19
Suppose you want to create the following pattern:
*
**
***
****
*****
Clearly, you want to print five lines of stars. In the first line you want to print one star, in
the second line two stars, and so on. Because five lines will be printed, start with the
following for statement:
for (i = 1; i <= 5; i++)
The value of i in the first iteration is 1 , in the second iteration it is 2 , and so on. You can
use the value of i as the limiting condition in another for loop nested within this loop to
control the number of stars in a line. A little more thought produces the following code:
for (i = 1; i <= 5; i++)
//Line 1
{
//Line 2
for (j = 1; j <= i; j++)
//Line 3
System.out.print("*");
//Line 4
System.out.println();
//Line 5
}
//Line 6
A walk-through of this code shows that the for loop, in Line 1, starts with i = 1 . When
i is 1 , the inner for loop, in Line 3, outputs one star and the insertion point moves to the
next line. Then i becomes 2 , the inner for loop outputs two stars, and the output
 
Search WWH ::




Custom Search