Right-Aligned Alphabet Pyramid in Java

What You’ll Learn
We use a simple trick: print a shrinking number of leading spaces, then print letters starting from A up to the current row letter.
Because letters use %2c, use a monospace font if you want the right edge to look perfect.
⭐ Pattern Output
Output for 5 rows:
A
A B
A B C
A B C D
A B C D EJava Program (Fixed A–E)
Fixed range A.. E, with one-space padding and %2c letters.
public class Main {
public static void main(String[] args) {
int i, j, k;
for (i = 65; i <= 69; i++) {
for (j = 69; j > i; j--) {
System.out.print(\" \");
}
for (k = 65; k <= i; k++) {
System.out.format(\"%2c\", k);
}
System.out.println();
}
}
}🧠 How It Works
Outer i
Sets the last letter for the current row: A through E.
Padding loop
Print one space while j > i. That is 'E' - i spaces, shrinking by 1 each row.
Letter loop
Print A.. i using System.out.format(\"%2c\", ...) so the sample spacing matches.
Constant visual width
Padding shrinks as the letter run grows, so the right margin stays aligned when printed in a monospace font.
Example row
At i = 'C', two padding spaces then three %2c letters. Five rows × O(n) inner work → O(n²) for n letters.
Variation — User Input
Let the user choose the number of rows. We compute endChar as 'A' + rows - 1, clamp to 1–26, and reuse the same loop structure.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print(\"Enter the number of rows: \");
int rows = sc.nextInt();
rows = Math.max(1, Math.min(rows, 26));
char startChar = 'A';
char endChar = (char) ('A' + rows - 1);
for (char i = startChar; i <= endChar; i++) {
for (char j = endChar; j > i; j--) {
System.out.print(' ');
}
for (char k = startChar; k <= i; k++) {
System.out.format(\"%2c\", k);
}
System.out.println();
}
sc.close();
}
}💡 Tips for Enhancement
Try These
- Left-align the pattern by removing the padding loop
- Use
\"%3c\"and adjust padding if you want wider columns - Validate
rowsto keep output withinA…Z
Avoid
- Expecting alignment in a proportional font
- Mixing double-space padding and
%2cwidth without checking spacing
Key Takeaways
Padding count per row is endChar - i spaces.
Letters per row is i - startChar + 1.
%2c matches the spaced sample output.
O(n²) work for n rows.
❓ Frequently Asked Questions
j == i, we want to stop padding and begin printing letters, so the condition is strictly j > i.More Java alphabet patterns
Once you understand padding and loop bounds, you can build many aligned triangles and pyramids.
Each step down removes one padding space and adds one more letter, so the right edge stays fixed when printed in a monospace font.
12 people found this page helpful
