Nested Loop Patterns and Dependent Bounds
Part of: Iteration
Beyond Rectangles When the inner loop's bounds depend on the outer loop variable, nested loops produce non-rectangular shapes like triangles and staircases. This is one of the most tested ideas in iteration. Dependent Inner Bounds Making the inner limit grow with the outer variable creates a right triangle: Row 1 prints 1 hash, row 2 prints 2, and so on. The total number of prints is 1 + 2 + 3 + 4 = 10, not a simple rectangle product. When inner bounds depend on the outer variable, you cannot just multiply, you must add up the rows. Counting Variable Work The pattern above does 1 + 2 + ... + n units of work, which equals n (n + 1) / 2. That is still roughly proportional to n squared for large n, even though it is about half the work of a full square. Avoiding Duplicate Pairs Dependent bounds are also how you generate unique pairs without repeats. Starting the inner loop at i + 1 ensures each pair is counted once: Tracing Strategy - Write out the inner range for the first few outer values: when row = 1, the inner runs col = 1; when row = 2, it runs col = 1, 2; and so on. - Sum those counts to get the total work. - Confirm the last row produces the widest output, which is the signatu
Challenge: Number Triangle