Two Diagonals (A..E)

Beginner
⏱️ 10 min read
📚 Updated: Aug 2025
🎯 2 Code Examples

⭐ Pattern Output

Output
A       A
 B     B
  C   C
   D D
    E
1

Node.js / console version

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

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

Browser version (document.write)

HTML
<!DOCTYPE html>
<html>
<body>
<script>
  const A = 65;
  const top = 69;
  for (let i = A; i <= top; i++) {
    for (let j = A; j <= top; j++) {
      if (i === j) document.write(String.fromCharCode(j));
      else document.write("&nbsp;&nbsp;");
    }
    for (let k = top - 1; k >= A; k--) {
      if (i === k) document.write(String.fromCharCode(k));
      else document.write("&nbsp;&nbsp;");
    }
    document.write("<br>");
  }
</script>
</body>
</html>

🧠 How It Works

1

Core idea

Outer i runs from A to E. First inner loop scans j = A..E and prints a letter only when i === j. Second inner loop scans k = D..A and prints a letter only when i === k. Other positions are blanks, creating two diagonals that meet in the middle.

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.

❓ Frequently Asked Questions

On the last row, the two diagonals meet at the center. Both inner checks point to the same position, so you only see a single E.
HTML collapses normal spaces, so the diagonal alignment breaks. Using &nbsp; (or fixed-width cells) preserves the grid spacing.
Change top from E to a later letter (for example "G".charCodeAt(0)). Keep the left scan as A..top and the right scan as top - 1..A.

More JavaScript alphabet patterns

Browse the full list for more variations.

Next: Program 32 →

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