Skip to main content

Learning outcomes

By the end of this lecture, you should be able to:
  • build triangular and number patterns
  • control row-dependent inner loop boundaries
  • trace nested loops with confidence

Pattern 1: right triangle of stars

n = 4
for i in range(1, n + 1):
    for j in range(i):
        print('*', end=' ')
    print()
Output:
*
* *
* * *
* * * *

Pattern 2: number triangle

n = 5
for i in range(1, n + 1):
    for j in range(1, i + 1):
        print(j, end=' ')
    print()

Pattern 3: multiplication grid

for i in range(1, 4):
    for j in range(1, 4):
        print(f"{i*j:>3}", end=' ')
    print()

Row-dependent boundaries

Key idea:
  • inner loop range often depends on i
  • this is what creates triangles and pyramids

Debug trap

Wrong:
for i in range(1, 5):
    for j in range(1, 5):
        print('*', end=' ')
    print()
This creates square, not triangle.
Fix: inner range should be range(1, i + 1).

Complexity intuition

  • triangular nested loops often perform about n(n+1)/2 steps
  • full grid loops perform n*n steps

Exam hints and traps

  • check whether inner loop limit is fixed or row-dependent
  • verify +1 inclusion in ranges
  • for pattern questions, write small dry-run for n = 3

Practice

  1. Print inverted star triangle.
  2. Print pattern:
1
1 2
1 2 3
1 2 3 4
  1. Write nested loop to print table from 2 to 4 side by side.