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: What usually goes wrong. What you see What caused it How to fix it --- --- --- Every number lands on one long line The line break was left out, or placed inside the inner loop Print the newline after the inner loop finishes, still inside the outer one Each row ends with a trai
Challenge: Multiplication Grid