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: What usually goes wrong. What you see What caused it How to fix it --- --- --- Every row holds n numbers The inner bound used n instead of the current row The inner limit has to depend on the outer counter Each row prints the same number repeated The body printed the r

Challenge: Number Triangle