Nested Loops JAVA UNIT 7 LOOPS Loopception Each
- Slides: 8
Nested Loops JAVA UNIT 7: LOOPS
Loop-ception Each loop contains a pair of brackets, with whatever code inside it being the body of the loop. Within those brackets, it is possible to add in more loops. It’s a loop within a loop. This is called nesting. You can nest as deep as you want.
We need to loop deeper while(i < loop. Count) { for(int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { … } } }
Uses Sometimes, you might want to run an operation that requires a loop multiple times. while(input. Val > 0) { int my. Sum = 0; for (int i = 1; i <= input. Val; i++) { my. Sum += i; } System. out. println(“” + my. Sum); input. Val = my. Scanner. next. Int(); }
Uses In the previous example, the inner ‘for’ loop would continually add in a value to the sum based on its loop index. The outer ‘while’ loop would handle user input, stopping if the user entered 0 or a negative number.
Uses It is also possible to write a pair of nested loops in such a way that the inner loop depends on the loop index of the outer loop. for (int i = 0; i < 20; i++) { for (int j = i; j < 20; j++) { … } }
Nesting ‘for’ loops For loops are an interesting case because of the pattern their loop indexes take on. Consider: for(int y = 0; y < 3; y++){ for(int x = 0; x < 3; x++) { System. out. println(“{“ + x + “, “ + y + “}, “); } } Output: {0, 0}, {1, 0}, {2, 0}, {0, 1}, {1, 1}, {2, 1}, … It’s almost like the two for loops are going through a table. In this case, the outer ‘for’ loop acts as a row counter, while the inner ‘for’ loop is a column counter.
Nesting ‘for’ loops For X=0 X=2 X=3 Y=0 {0, 0} {1, 0} {2, 0} Y=1 {0, 1} {1, 1} {2, 1} Y=2 {0, 2} {1, 2} {2, 2}