Java Notes
A nested loop places one loop inside another. It is used for rows and columns, comparisons between pairs, and two-dimensional data.
A nested loop is a loop inside another loop. For every one iteration of the outer loop, the inner loop completes all of its iterations. This is useful for tables, grids, matrices, and comparisons between pairs of values.
Rows and columns
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
The outer row loop runs three times. During each row, the inner column loop runs four times, so the body executes 3 × 4 = 12 times.
Multiplication table
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
The blank println() separates one number's table from the next. Using meaningful names such as number and multiplier is easier to read than using i and j in longer code.
Two-dimensional arrays
Nested loops naturally visit values in a two-dimensional array.
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
Use marks.length for the number of rows and marks[row].length for the number of values in the current row. Rows do not have to be the same length.
Cost of nested loops
If the outer and inner loops each run n times, the body runs roughly n × n, written as O(n²). That is acceptable for small grids, but it can become slow with large data.
| Work | Typical loop shape | Approximate cost |
|---|---|---|
| Visit every value in one list | One loop | O(n) |
Visit every cell in an n × n grid | Two nested loops | O(n²) |
| Compare every pair from two lists | Two nested loops | O(a × b) |
Do not avoid nested loops when a problem genuinely has rows and columns. Avoid them only when they repeatedly search the same large data and a better structure, such as a map or set, can do the job.
What to remember
- The inner loop completes for every outer-loop iteration.
- Nested loops are useful for tables, matrices, patterns, and pairwise comparisons.
- Count how many times each loop runs to understand the total work.
- Use descriptive variable names when loop logic is more than a few lines.
Continue the lesson path