Centered Pyramid (A to i)

Beginner
⏱️ 8 min read
📚 Updated: Aug 2025
🎯 2 Code Examples
Indent + letters

What You'll Learn

This program prints a centered pyramid. For each row, we print some indentation, then print letters from A up to the row letter, separated into cells so spacing stays consistent.

⭐ Pattern Output

Output
    A
   A B
  A B C
 A B C D
A B C D E
1

Node.js / console version

Build the line with indentation and letters, then log it.

JavaScript
const A = "A".charCodeAt(0);
const top = "E".charCodeAt(0);

for (let i = A; i <= top; i++) {
  let line = "";
  for (let j = top; j > i; j--) line += "  ";
  for (let k = A; k <= i; k++) line += String.fromCharCode(k) + " ";
  console.log(line.trimEnd());
}
2

Browser version (document.write + div)

Reference-style output: use &nbsp; for indentation and fixed-width cells for letters.

HTML
<!DOCTYPE html>
<html>
<head>
  <style>
    div.cell {
      display: inline-block;
      text-align: center;
      width: 18px;
    }
  </style>
</head>
<body>
<script>
  const A = 65;
  const top = 69;
  for (let i = A; i <= top; i++) {
    for (let j = top; j > i; j--) document.write("&nbsp;&nbsp;");
    for (let k = A; k <= i; k++) document.write("<div class=\\"cell\\">" + String.fromCharCode(k) + "</div>");
    document.write("<br>");
  }
</script>
</body>
</html>

🧠 How It Works

1

Core idea

Outer i runs from A to E. First inner loop prints indentation (two spaces per step) while j > i. Second loop prints A..i using String.fromCharCode, producing a centered pyramid.

Logic
2

Loops + condition

An outer loop picks the row, inner loop(s) decide what to print (letter / star / blank) based on comparisons.

Nested loops
=

Connect it to the output

Compare each loop boundary with the pattern output above — each row corresponds to one outer iteration.

Key Takeaways

1

Indentation prints before letters to center the pyramid.

2

Letters print from A to i each row.

3

Fixed-width cells prevent spacing issues in HTML.

4

Time complexity: O(n²).

❓ Frequently Asked Questions

HTML collapses whitespace, so multiple spaces won’t align reliably. &nbsp; or fixed-width cells preserve spacing.
Yes. Remove the added " " in the Node.js example (and adjust the HTML cell width if needed).
Set top to a later letter (e.g., "H".charCodeAt(0) / 72) and the loops will scale.

More JavaScript alphabet patterns

Browse the full list for more variations.

Next: Program 28 →
Did you know?

The indentation loop runs \(top - i\) times, so the pyramid shifts left one step each row.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

10 people found this page helpful