S3Q2 · Print Pattern - X Shape¶
⚡ Quick Reference
Type: Full I/O - pattern printing
Core idea: top half has \ and / converging inward; bottom half mirrors with / and \ diverging outward.
n = int(input())
# Top half
for i in range(1, n + 1):
pad = " " * (i - 1)
inner = " " * (2 * (n - i) + 1)
print(pad + "\\" + inner + "/")
# Centre
print(" " * n + "x")
# Bottom half
for j in range(1, n + 1):
pad = " " * (n - j)
inner = " " * (2 * (j - 1) + 1)
print(pad + "/" + inner + "\\")
Key rules:
- Top row i (1-indexed): leading=i-1, inner=2*(n-i)+1
- Centre: n leading spaces then x
- Bottom row j (1-indexed): leading=n-j, inner=2*(j-1)+1
- No trailing spaces - / or \ is always the last character
Problem Statement¶
Problem (I/O type)
Given n, print an X-shaped pattern. The top half has \ and / converging toward the centre; the bottom half has / and \ diverging from it. n=0 prints just x.
Examples:
2
\ /
\ /
x
/ \
/ \
1
\ /
x
/ \
Deriving the formulas¶
For n=2:
Top half (row i from 1 to n):
- Leading spaces = i - 1
- Inner spaces = 2*(n-i) + 1
Centre: n leading spaces + x
Bottom half (row j from 1 to n):
- Leading spaces = n - j
- Inner spaces = 2*(j-1) + 1
Top and bottom are mirrors
The bottom half is the vertical mirror of the top half. The leading/inner space formulas swap: top row 1 has (0, 3) and bottom row n also has (0, 3). This symmetry is why the X looks symmetric.
Tracing n = 2¶
Top half:
| i | leading | inner | Row |
|---|---|---|---|
| 1 | 0 | 3 | \···/ |
| 2 | 1 | 1 | ·\/ → ·\ / |
Centre: 2 spaces + x → ··x
Bottom half:
| j | leading | inner | Row |
|---|---|---|---|
| 1 | 1 | 1 | ·/·\ → / \ |
| 2 | 0 | 3 | /···\ → / \ |
Solution approaches¶
n = int(input())
# Top half - \ converges right, / converges left
for i in range(1, n + 1):
leading = " " * (i - 1)
inner = " " * (2 * (n - i) + 1)
print(leading + "\\" + inner + "/")
# Centre
print(" " * n + "x")
# Bottom half - / diverges left, \ diverges right
for j in range(1, n + 1):
leading = " " * (n - j)
inner = " " * (2 * (j - 1) + 1)
print(leading + "/" + inner + "\\")
Edge case: n = 0¶
Only the centre is printed - print(" " * 0 + "x") = "x". Both loops run zero times.
Key takeaways¶
Inner spaces formula: 2*(n-i)+1
The gap between \ and / starts at 2n-1 (row 1) and shrinks by 2 each row, reaching 1 just before the centre. The formula 2*(n-i)+1 captures this.
Top and bottom are symmetric
The bottom half is the top half flipped vertically, with / and \ swapped. The leading/inner formulas simply exchange roles between i and j.
Always escape backslash: \\
"\\" in Python produces a single \ character. Forgetting the escape is the most common bug in patterns using backslashes.