Right-Aligned Number Triangle in C#

What You’ll Learn
How to print a right-aligned triangle where each row prints numbers from 1 to the row number.
We first print spaces, then print numbers using a fixed width so the output looks aligned.
⭐ Pattern Output
For rows = 5, the pattern looks like this:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5Complete C# Program
Print leading spaces to right-align, then print 1..i using {0,2} formatting.
using System;
namespace MyApp
{
class Program
{
static void Main(string[] args)
{
int rows = 5;
int i, j, k;
for (i = 1; i <= rows; i++)
{
for (j = rows; j > i; j--)
Console.Write(" ");
for (k = 1; k <= i; k++)
Console.Write("{0,2}", k);
Console.WriteLine();
}
}
}
}🧠 How It Works
Outer loop controls rows
i runs from 1 to rows.
First inner loop prints spaces
The loop for (j = rows; j > i; j--) prints fewer spaces as i grows.
Second inner loop prints numbers
for (k = 1; k <= i; k++) prints 1..i on each row.
Fixed-width formatting keeps alignment
{0,2} ensures each number takes 2 characters, so columns stay neat.
Variation — User Input Rows
Let the user choose the number of rows at runtime.
using System;
namespace MyApp
{
class Program
{
static void Main(string[] args)
{
int rows;
Console.Write("Enter number of rows: ");
if (!int.TryParse(Console.ReadLine(), out rows) || rows <= 0)
{
Console.WriteLine("Please enter a positive integer.");
return;
}
for (int i = 1; i <= rows; i++)
{
for (int j = rows; j > i; j--)
Console.Write(" ");
for (int k = 1; k <= i; k++)
Console.Write("{0,2}", k);
Console.WriteLine();
}
}
}
}💡 Tips for Enhancement
Try These
- Change
{0,2}to{0,3}for larger row counts - Print the triangle left-aligned by removing the space loop
- Print descending numbers by looping
kfromidown to 1
Avoid
- Forgetting the newline after each row
- Using too small a field width when numbers reach two digits
Key Takeaways
Leading spaces shift the triangle to the right.
The numbers are simply 1..i for each row.
Fixed-width printing keeps columns aligned.
Total prints are triangular \(\Rightarrow\) O(n²).
Explore More C# Number Patterns!
Triangle patterns are a great starting point for mastering nested loops.
Many console patterns can be built by combining an indentation loop (spaces) with a printing loop (numbers or symbols).
12 people found this page helpful
