MASTER YOUR LOGIC BUILDING:Phase 6 - Category 4: Nested Logic & Patterns

Mastering phase 6 - category 4: nested logic & patterns concepts and implementation.

Nested Logic & Patterns

Why This Matters

A multiplication table is a grid — every row crossed with every column. Finding pairs in a list that add up to a target means checking every combination. These problems need a loop inside another loop — nested logic. It's like checking every seat in every row of a cinema: the outer loop picks the row, the inner loop walks through seats.

What You'll Learn

  • How nested loops work (outer loop = rows, inner loop = columns)
  • How to print grids like multiplication tables
  • How to find pairs in an array that meet a condition
  • How to spot the pattern before writing code

How Nested Loops Work

for i in range(1, 4):       # outer: 1, 2, 3
    for j in range(1, 4):   # inner: runs fully for EACH i
        print(i, j, end="  ")
    print()                 # new line after each row

Output:

1  1  1  2  1  3
2  1  2  2  2  3
3  1  3  2  3  3

For each value of i, the inner loop runs completely. Total iterations = 3 × 3 = 9.

Step-by-Step: Multiplication Table

Print a 5×5 grid where each cell shows row × column:

  1. Outer loop i = rows (1 to 5)
  2. Inner loop j = columns (1 to 5)
  3. Print i * j, then move to next column
  4. After inner loop finishes, print a newline
n = 5
for i in range(1, n + 1):
    for j in range(1, n + 1):
        print(f"{i * j:4}", end="")
    print()

The :4 formats numbers in a fixed width so columns line up nicely.

Finding Pairs with a Target Sum

Given [2, 4, 3, 5, 1] and target 6, find pairs that add to 6: (2, 4), (3, 3), (5, 1).

arr = [2, 4, 3, 5, 1]
k = 6

for i in range(len(arr)):
    for j in range(i + 1, len(arr)):   # start j AFTER i — avoids duplicates
        if arr[i] + arr[j] == k:
            print(f"({arr[i]}, {arr[j]})")

Why `j` starts at `i + 1`? So you don't print (2, 4) and (4, 2) twice, and you don't pair an element with itself.

Reading a Pattern Before Coding

For any pattern problem, ask:

  1. How many rows? → outer loop count
  2. How many columns per row? → inner loop count
  3. What formula? → what to print at position (i, j)?
  4. Any spacing? → leading spaces for pyramids/diamonds

Draw the first 3 rows on paper. The pattern usually becomes obvious.

Common Mistakes & Tips

  • Swapping outer and inner loop roles — decide which variable represents "row" and which represents "column"
  • Printing without newline — use print() after the inner loop to start a fresh row
  • Duplicate pairs — when finding pairs, always start inner index from i + 1
  • Infinite loops — make sure inner loop doesn't reset something the outer loop depends on incorrectly
  • Tip: Start with n = 3 or n = 4 when testing patterns — smaller output is easier to verify

Practice Focus

  • Print a multiplication table for any number n
  • Find all pairs in an array with a given sum
  • Print a simple number triangle (1, 12, 123, ...)
  • Print a square pattern of stars (n rows, n stars each)
  • Check how many pairs of elements in a list are equal

Nested loops feel slow at first, but they're one of the most powerful tools in programming. Row by row, column by column — you've got this!

Hands-on Examples

Multiplication Table Grid

# Take n as input
n = int(input("Enter number: "))

# Print multiplication table
print(f"Multiplication table for {n}:")
for i in range(1, n + 1):
    for j in range(1, n + 1):
        product = i * j
        print(f"{product:4}", end="")  # Format with width 4
    print()  # New line after each row

Use nested loops: outer loop for rows (i), inner loop for columns (j). Print product i*j. Format output for alignment.