Pattern 14
EasyAlphabet triangle A, AB, ABC
Problem
Print an alphabet triangle A, AB, ABC, … for a given size n.
Use one loop for the rows and another for what goes in each row to draw the shape.
The idea
Identical to the number triangle, except the printed value is a letter derived from the column index. In C++ and Java `'A' + j` is a character; in Python use `chr(ord('A') + j)`.
The trick
- Characters are just small integers — arithmetic on them works.
rows5
Step 1 of 7. Alphabet triangle: A, AB, ABC, … rows 5.
1/7
Optimal
timeO(n^2)spaceO(1)
1// n = 5 produces:2// A3// A B4// A B C5// A B C D6// A B C D E7 8for i in 1..n:9 for j in 0..i-1: print(char('A'+j))10 newlineInput
- grid
- 5 × 5
Memory
- rows
- 5
Output
- printed rows
- —
- rows
- 5
Check yourself
3 quick questions about this walkthrough. A wrong answer costs nothing.
Example
- Input:
- n = 5
- Output:
- A / A B / A B C / A B C D / A B C D E
Finished the walkthrough? Add it to your streak.