Print Character Triangle in Java
Problem
Since a char is really just a small integer under the hood, adding an offset to 'A' walks through the alphabet the same way adding to a loop counter walks through numbers.
Given a number of rows, print a left-aligned triangle where row i contains the first i letters of the alphabet.
Java Program
public class CharacterTriangle {
public static void main(String[] args) {
int n = 5;
for (int i = 1; i <= n; i++) {
StringBuilder row = new StringBuilder();
for (int j = 0; j < i; j++) {
if (j > 0) row.append(" ");
row.append((char) ('A' + j)); // 'A' + j walks forward through the alphabet
}
System.out.println(row);
}
}
}Output
Core Logic
Casting an integer offset onto the letter 'A' turns the same row-and-column counting used for a star triangle into a sequence of letters instead.
- 1The outer loop runs
ifrom1ton, one pass per row. - 2The inner loop runs
jfrom0toi - 1, one pass per letter in that row. - 3
(char) ('A' + j)converts the column index directly into the matching letter, sincecharvalues are just numeric codes underneath. - 4Each row's letters are joined with single spaces and printed once the inner loop finishes.
j runs 0 through 3, producing 'A'+0, 'A'+1, 'A'+2, 'A'+3 — the letters A B C D.Key Point: The inner loop never needs to know it's building letters instead of numbers — only the single line that converts j into a character changes from a numeric pattern.
Why: The total letters printed across every row grows proportionally to n², and only the loop counters and a per-row StringBuilder are kept at any point.
Key Concepts
Approach 2: Java 8
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class CharacterTriangleStream {
public static void main(String[] args) {
int n = 5;
IntStream.rangeClosed(1, n)
.mapToObj(i -> IntStream.range(0, i)
.mapToObj(j -> String.valueOf((char) ('A' + j)))
.collect(Collectors.joining(" ")))
.forEach(System.out::println);
}
}
Output
Core Logic
The same row-by-row letter sequence can be produced by mapping each row's column indices directly to their letters and joining the results.
- 1
IntStream.rangeClosed(1, n)generates one stream element per row. - 2For each row
i, an innerIntStream.range(0, i)generates that row's column indices. - 3
.mapToObj(j -> String.valueOf((char) ('A' + j)))converts each column index into its letter. - 4
Collectors.joining(" ")joins that row's letters with spaces beforeforEachprints it.
0, 1, 2, 3 to A, B, C, D and joins them into "A B C D".Key Point: Nesting one stream inside another mirrors the nested loop exactly — the outer stream picks the row, the inner stream builds that row's content.
Why: The nested streams still visit every letter position across every row exactly once, without collecting the full triangle into a stored structure.