Java Reference
In-Depth Information
Tip 6.1 ). Instead, make the for loop control a single counter, and update the other
variable explicitly:
int j = 10;
for (int i = 0; i <= 10; i++)
{
. . .
j--;
}
6.3 Nested Loops
Sometimes, the body of a loop is again a loop. We say that the inner loop is nested
inside an outer loop. This happens often when you process two-dimensional
structures, such as tables.
Loops can be nested. A typical example of nested loops is printing a table with
rows and columns.
Let's look at an example that looks a bit more interesting than a table of numbers. We
want to generate the following triangular shape:
The basic idea is simple. We generate a sequence of rows:
for (int i = 1; i <= width; i++)
{
// Make triangle row
. . .
}
How do you make a triangle row? Use another loop to concatenate the squares [] for
that row. Then add a newline character at the end of the row. The i th row has i
symbols, so the loop counter goes from 1 to i .
Search WWH ::




Custom Search