Right-Aligned Number Triangle (1 to i)

What You’ll Learn
How to print a triangle where each row prints 1 to i, and spaces are printed before the numbers to make it right-aligned.
This is a great exercise for mastering nested loops and formatting output.
⭐ Pattern Output
For size = 5, the pattern looks like this:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5Complete JavaScript Program
We first print indentation spaces, then we print numbers from 1 to the row number.
const size = 5;
for (let i = 1; i <= size; i++) {
let line = "";
// indentation (2 spaces per missing number)
for (let j = size; j > i; j--) {
line += " ";
}
for (let k = 1; k <= i; k++) {
line += k + " ";
}
console.log(line.trimEnd());
}🧠 How It Works
Set rows
size = 5 prints 5 rows.
Row loop (i)
For each row i, we build a single output line.
Indentation loop (j)
We add size - i indentation blocks. As i increases, indentation shrinks.
Number loop (k)
Then we print numbers from 1 to i on the same line.
Right-aligned triangle
Indentation + increasing numbers creates the right-aligned shape.
Variation — Browser (document.write) Version
This is the same logic as the old reference: print indentation using , then print numbers from 1..i.
<!DOCTYPE html>
<html>
<body>
<script>
var i, j, k;
for (i = 1; i <= 5; i++) {
for (j = 5; j > i; j--)
document.write(" ");
for (k = 1; k <= i; k++)
document.write(k + " ");
document.write("<br>");
}
</script>
</body>
</html>💡 Tips for Enhancement
Try These
- Change
sizeto print more (or fewer) rows - Replace
kwithk*kto print squares - Print each row as a string first (cleaner formatting)
- Use monospace fonts for perfect alignment
Avoid
- Using normal spaces in HTML (they collapse); prefer
- Forgetting to decrease indentation (triangle won’t align)
- Leaving trailing spaces (use
trimEnd()in console output)
Key Takeaways
Use nested loops to print rows and columns (spaces + numbers).
Indentation count is size - i for a right-aligned triangle.
Each row prints a simple sequence from 1 to i.
is essential for aligned HTML output.
❓ Frequently Asked Questions
1), so using two spaces for indentation keeps the columns visually aligned.k from 0 and print up to i - 1.join(" "), then add indentation before it.Explore More JavaScript Number Patterns!
Once you master indentation + loops, you can create many centered/right-aligned patterns easily.
Many “centered” and “right-aligned” patterns are just left-aligned patterns with a prefix of spaces. Once you control indentation, you can shape the output however you want.
12 people found this page helpful
