Nested Loops

Part of: Iteration

Loops Inside Loops A nested loop is a loop placed inside the body of another loop. The outer loop controls how many times the inner loop runs from start to finish. For every single pass of the outer loop, the inner loop completes all of its iterations. Counting Total Iterations If the outer loop runs m times and the inner loop runs n times per outer pass, the inner body executes m n times in total. This multiplication is the central idea of nested loops. This prints a 3-by-4 grid of stars: the inner body runs 3 4 = 12 times. Rows and Columns Nested loops naturally model rows and columns . By convention the outer variable is the row and the inner variable is the column. A frequent mistake is forgetting the System.out.println() after the inner loop, which would jam everything onto one line. Order of Output When tracing nested loops, remember the inner loop finishes completely before the outer loop advances: Tracing Tips - A for header re-initializes its variable every time the inner loop starts, so the inner counter resets automatically. - Track the order of output carefully, the inner loop exhausts all its values before the outer advances. - Watch where each print versus println goe

Challenge: Multiplication Grid