Python Program to Print Alphabet Triangle Pattern
for i in range(1, n+1): print(''.join(chr(64+j) for j in range(1, i+1))) where n is the number of rows.Examples
How to Think About It
Algorithm
Code
n = int(input('Enter number of rows: ')) for i in range(1, n + 1): row = ''.join(chr(64 + j) for j in range(1, i + 1)) print(row)
Dry Run
Let's trace input 3 through the code
Input number of rows
n = 3
First row (i=1)
Generate letters from 1 to 1: chr(64+1) = 'A'; print 'A'
Second row (i=2)
Generate letters from 1 to 2: chr(64+1)='A', chr(64+2)='B'; print 'AB'
Third row (i=3)
Generate letters from 1 to 3: 'A', 'B', 'C'; print 'ABC'
| Row (i) | Letters Generated | Printed Output |
|---|---|---|
| 1 | A | A |
| 2 | A B | AB |
| 3 | A B C | ABC |
Why This Works
Step 1: Loop through rows
The outer loop runs from 1 to n, controlling how many rows to print.
Step 2: Generate letters for each row
The inner part uses chr(64 + j) to convert numbers to letters starting from 'A' (ASCII 65).
Step 3: Print the row
Joining letters into a string and printing creates the triangle shape line by line.
Alternative Approaches
n = int(input('Enter number of rows: ')) for i in range(n): for j in range(i + 1): print(chr(65 + j), end='') print()
import string n = int(input('Enter number of rows: ')) alphabets = string.ascii_uppercase for i in range(1, n + 1): print(alphabets[:i])
Complexity: O(n^2) time, O(n) space
Time Complexity
The program uses nested loops: the outer loop runs n times and the inner loop runs up to n times, resulting in O(n^2) time.
Space Complexity
The space used is mainly for the string of letters in each row, which grows up to length n, so O(n) space.
Which Approach is Fastest?
All approaches have similar time complexity; using string slicing is more readable but uses extra memory for the alphabet string.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Using chr() with join | O(n^2) | O(n) | Simple and clear for beginners |
| Nested loops with print | O(n^2) | O(1) | Memory efficient, prints directly |
| String slicing | O(n^2) | O(n) | Readable and uses built-in strings |
chr(65 + index) to convert numbers to uppercase letters starting from 'A'.