09

Phase 2 - Level 4: Pattern Printing

Chapter 9 • Intermediate

90 min

Phase 2 - Level 4: Pattern Printing

Introduction

Pattern printing is an excellent way to master nested loops and understand how loops work together. You'll print various patterns using stars, numbers, and characters.

Key Concepts

Nested Loops

  • Outer loop: Controls rows
  • Inner loop: Controls columns
  • Pattern logic: Determine what to print at each position

Common Patterns

Right Triangle

code
*
**
***
****

Inverted Right Triangle

code
****
***
**
*

Pyramid

code
    *
   ***
  *****
 *******

Number Patterns

code
1
12
123
1234

Pattern Analysis Steps

  1. Count Rows: How many rows?
  2. Count Columns: How many columns per row?
  3. Determine Logic: What to print at (row, col)?
  4. Handle Spacing: Add spaces for alignment

Common Techniques

  • Row-based: Outer loop for rows, inner for columns
  • Spacing: Calculate spaces before stars
  • Conditional Printing: Print based on position
  • Character Patterns: A, AB, ABC sequences

Tips

  • Start with simple patterns (right triangle)
  • Understand relationship between row and column
  • Use print() with end="" to control output
  • Test with small values first

Hands-on Examples

Print Right Triangle Pattern

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

# Print right triangle
for i in range(1, n + 1):
    for j in range(1, i + 1):
        print("*", end="")
    print()  # New line after each row

Outer loop (i) controls rows. Inner loop (j) prints i stars. After each row, print newline.