Java Reference
In-Depth Information
Nested Loops
The body of a loop can contain another loop. This situation is called a nested
loop. Keep in mind that for each iteration of the outer loop, the inner loop exe-
cutes completely. Consider the following code fragment. How many times does
the string "Here again" get printed?
int count1, count2;
count1 = 1;
while (count1 <= 10)
{
count2 = 1;
while (count2 <= 50)
{
System.out.println ("Here again");
count2++;
}
count1++;
}
The println statement is inside the inner loop. The outer loop executes 10 times,
as count1 iterates between 1 and 10. The inner loop executes 50 times, as count2
iterates between 1 and 50. For each iteration of the outer loop, the inner loop
executes completely. Therefore the println statement is executed 500 times.
As with any loop situation, we must be careful to scrutinize the conditions of
the loops and the initializations of variables. Let's consider some small changes to
this code. What if the condition of the outer loop were (count1 < 10) instead of
(count1 <= 10) ? How would that change the total number of lines printed? Well,
the outer loop would execute 9 times instead of 10, so the println statement
would be executed 450 times. What if the outer loop were left as it was originally
defined, but count2 were initialized to 11 instead of 1 before the inner loop? The
inner loop would then execute 40 times instead of 50, so the total number of lines
printed would be 400.
Let's look at another example that uses a nested loop. A palindrome is a string
of characters that reads the same forward or backward. For example, the follow-
ing strings are palindromes:
radar
drab bard
ab cde xxxx edc ba
kayak
deified
able was I ere I saw elba
 
Search WWH ::




Custom Search