Topic 6 Nested for Loops
"Complexity has and will maintain a strong fascination for many people. It is true that we live in a complex world and strive to solve inherently complex problems, which often do require complex mechanisms. H thi h ld t di i i h d i f l t l ti hi h However, this should not diminish our desire for elegant solutions, which convince by their clarity and effectiveness. Simple, elegant solutions are more effective, but they are harder to find than complex ones, and they require more time which we too often believe to be unaffordable " require more time, which we too often believe to be unaffordable
- Niklaus Wirth
Based on slides for Building Java Programs by Reges/Stepp, found at http://faculty.washington.edu/stepp/book/
CS305j Introduction to Computing Nested For Loops
1
p y g pp
Nested for loops
A for loop can contain any kind of statement in its body, including another for loop.
– The inner loop must have a different name for its loop counter i bl th t it ill t fli t ith th t l variable so that it will not conflict with the outer loop.
nested loop: Loops placed inside one another, creating a loop of loops.
for (int i = 1; i <= 3; i++) { for (int j = 1; j <= 2; j++) { System.out.println("six"); } }
Output: six six six six six six six
CS305j Introduction to Computing Nested For Loops
2
More nested for loops
All of the statements in the outer loop's body are All of the statements in the outer loop s body are executed 5 times.
– The inner loop runs 10 times for each of those 5 times, for a total of 50 numbers printed. for (int i = 1; i <= 5; i++) { for (int j = 1; j <= 10; j++) { System.out.print((i * j) + " "); } S t t i tl () // t d th System.out.println(); // to end the line }
Output: 1 2 3 4 5 6 7 8 9 10 2 4 6 8 10 12 14 16 18 20 3 6 9 12 15 18 21 24 27 30
CS305j Introduction to Computing Nested For Loops
3
4 8 12 16 20 24 28 32 36 40 5 10 15 20 25 30 35 40 45 50
Nested for loop exercise
Wh t i th t t f th f ll i t d What is the output of the following nested for loop?
for (int i = 1; i <= 4; i++) { for (int j = 1; j <= 5; j++) { S i ("*") System.out.print("*"); } System.out.println(); }
Output? Output? Do you really need a nested for loop in this case?
CS305j Introduction to Computing Nested For Loops
4