Tricky · Pattern

Main Diagonal

Main Diagonal

Tricky

Symbol pattern, solid style, size 5. Changing the rubric, style or size above re-shapes the loops — the structure stays identical while only the printed value or the cell filter changes.

Main Diagonal · output

Symbol · Solid · size 5

max 9
     
     
     
     
     
1 / 12
Drawing… ready to start.
Python · Main Diagonal · Python
n = int(input("Enter number of rows: "))

# Diagonal cross — the two diagonals, walking value 1, 2, 3, ...
for i in range(1, n + 1):
    lft = min(i - 1, n - i)
    for j in range(1, n + 1):
        if (i == j or i + j == n + 1):
            if i == j:
                print('*', end='')
            else:
                print('*', end='')
        else:
            print(' ', end='')
    print()

Behind the Scenes Execution

registers · line tracking · call stack · memory regions
PC0x4000SP0x7FE8FLAGSZF 0OPenter function
Call Stack
main()@0x7FD0
n = 5i = -1j = -1count = 0
Memory Map
AddressVariableValue
Stack (4)
0x200n5
0x204i-1
0x208j-1
0x20Ccount0
String Pool (static) (2)
0x400000pool["*"]*
0x400008pool["\n"]\n
Heap (5)
0x3000grid[0]
0x3020grid[1]
0x3040grid[2]
0x3060grid[3]
0x3080grid[4]
1 / 12
Tricky

Main Diagonal

Just the main diagonal: each row is filled with spaces and exactly one value at column i — value i + j + 1. It isolates the diagonal walk from everything else.

The size-5 grid

Only the main diagonal is painted: five cells at (0, 0) through (4, 4) carrying the values 1, 3, 5, 7, 9 from r + c + 1. Every other cell is a space, so the frame stays 5 by 5 with twenty blanks.

Off-by-one traps

Value 2r + 1 is only correct because the diagonal has c == r; printing i + j + 1 is fine there, but adding a row offset as well shifts the values off the diagonal.

Step by step

  1. Type n when the program asks.
  2. Loop i = 1 to n, and set lft = min(i - 1, n - i).
  3. Inner loop j = 1 to n.
  4. On the main diagonal (i == j) print the diagonal walk value; a space otherwise.
  5. Newline after every row.

Complexity

BestO(n²)
AverageO(n²)
WorstO(n²)
SpaceO(1) if printed directly

When to use it

  • Sparse diagonals
  • Index-equation drills
Study tip: pick a size, then run and step through the execution. Watch the grid[r] rows in the Heap region and the i / j / count registers on the Stack — every printed character is one write to the grid.

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits