Right-Aligned Number Triangle in C#

Beginner
⏱️ 9 min read
📚 Updated: Aug 2026
🎯 3 Code Examples
🚀 Live Preview
Nested Loops + Formatting

What You’ll Learn

The right-aligned number triangle prints 1, then 1 2, then 1 2 3, … — a natural follow-up after Program 42’s hollow square border. This tutorial covers leading-space indentation, ascending sequences, fixed-width formatting, nested loops, a live preview, worked C# examples, edge cases, and complexity.

Shape Rule

Right-aligned triangle

Row i prints numbers 1 to i, with leading spaces before the digits.

Outer Loop

i = 1..rows

for (i = 1; i <= rows; i++) — ascending outer loop, one row per iteration.

Space Loop

rows..i+1

for (j = rows; j > i; j--) — prints a single space for right alignment.

Number Loop

{0,2} format

for (k = 1; k <= i; k++) then Console.Write("{0,2}", k).

Live Preview

3–7 rows

Pick a row count and draw the right-aligned number triangle in the browser.

O(n²)

Complexity

Total prints = n(n+1)/2 — work scales as .

Introduction

A right-aligned number triangle prints numbers from 1 to i on each row: 1, then 1 2, then 1 2 3, and so on. With rows = 5, shorter rows shift right thanks to a leading-space loop.

In C# you use three nested loops: print a space while j > i, then print Console.Write("{0,2}", k) for k = 1..i, then WriteLine().

Why it matters?

It combines a space loop with an ascending number loop — a key step after Program 42’s hollow grid pattern.

Key Highlights

1..i

Ascending sequence.

Space loop

j > i spaces.

{0,2}

Fixed-width columns.

Series Foundation

Follow Program 42; continue to Program 44 next.

In short: outer i = 1..rows, space loop j = rows..i+1, numbers k = 1..i with {0,2}, then WriteLine().

📝 Problem & Approach

Given rows = 5, print a right-aligned ascending triangle: leading spaces while j > i, then numbers from 1 to i with fixed-width formatting.

C#
// rows = 5
//    1
//   1 2
//  1 2 3
// 1 2 3 4
//1 2 3 4 5

Inputs & Outputs

ItemTypeDescription
rowsintTriangle height — also controls leading-space count.
iintOuter loop — current row number (1 to rows).
jintSpace loop — prints leading spaces while j > i.
kintNumber loop — prints digits 1..i.

Minimal workflow

Pseudocode
for i from 1 to rows:
    for j from rows down to i+1: print one space
    for k from 1 to i: print k in width 2
    print newline

Approach comparison

ApproachIdeaBest for
Fixed rows1, 1 2, …Learning and interviews
User-input rowsint.TryParse(...)Configurable triangle size
Left-aligned variantRemove space loopContrast with right alignment

⚡ Quick Reference

GoalPattern
Outer loopfor (i = 1; i <= rows; i++)
Space loopfor (j = rows; j > i; j--) Console.Write(" ");
Number loopfor (k = 1; k <= i; k++)
Print numberConsole.Write("{0,2}", k);
End the rowConsole.WriteLine();
Program 42 contrastHollow square grid — not an ascending triangle

📋 Fixed vs User Input vs Left-Aligned

Same ascending triangle — different ways to control rows and alignment.

Outer loop
i = 1..rows

One row per iteration

Spaces
j > i

Leading-space indent

Numbers
k = 1..i

Ascending sequence

Left-aligned
skip space loop

Flush-left triangle

Context

When This Pattern Shows Up

Reach for this pattern when teaching dual inner loops, ascending sequences, and right-aligned console output.

  1. After Program 42

    Natural follow-up — moves from a 2D grid with border conditions to a triangle with leading spaces and ascending digits.

  2. Dual inner-loop drills

    Practice separating space printing from number printing before tackling more complex shapes.

  3. Console I/O practice

    Combine loops with ReadLine and TryParse for flexible row counts.

  4. Gateway to variants

    Compare Program 42 (hollow square) and Program 44 (next in series) next.

  5. Not a UI layout tool

    This is a console teaching pattern — not how you build modern app screens.

Key benefit: one small program that locks in dual inner loops, formatted output, and O(n²) thinking.

🔮 Live Preview

Choose a row count between 3 and 9 and draw the right-aligned number triangle in the browser.

Try 3, 5, or 7. Rows between 3 and 9 in this preview.

Live result
Press "Draw pattern".

Examples Gallery

Three complete C# programs — fixed rows, user input, and a smaller trace demo. Click View Output to reveal sample console results.

📚 Getting Started

Print five rows of the right-aligned number triangle with space and number loops.

Example 1 — Fixed rows = 5

Hard-coded row count — ideal for first demos and screenshots.

C#
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

When i = 1, the space loop prints four spaces, then 1. When i = 5, no leading spaces — output 1 2 3 4 5 with fixed-width columns.

📈 User Input

Read the row count from the console instead of hard-coding 5.

Example 2 — User input rows

Read rows from the console with safe parsing.

C#
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();
            }
        }
    }
}

How It Works

Same space-and-number loop core as Example 1; only rows comes from user input instead of being hard-coded as 5.

⚡ Left-Aligned Contrast

Remove the space loop to see how right alignment changes the shape.

Example 3 — Left-Aligned Triangle

Same ascending sequence without leading spaces — numbers start flush left.

C#
using System;

namespace MyApp
{
    class Program
    {
        static void Main(string[] args)
        {
            int rows = 5;

            for (int i = 1; i <= rows; i++)
            {
                for (int k = 1; k <= i; k++)
                    Console.Write("{0,2}", k);

                Console.WriteLine();
            }
        }
    }
}

How It Works

Only the space loop is removed — the number loop and {0,2} formatting stay the same. Compare this flush-left output with Example 1 to see what the space loop contributes.

🧠 How the Algorithm Prints Rows

1

Set up

using System; brings in Console. Set loop variables i, j, k with rows = 5.

Setup
2

Outer loop walks rows

for (i = 1; i <= rows; i++) — ascending outer loop; one row per iteration.

Row
3

Space loop

for (j = rows; j > i; j--) — prints a single space for right alignment.

Align
4

Number loop

for (k = 1; k <= i; k++) then Console.Write("{0,2}", k) — ascending sequence.

Print
5

New line

Console.WriteLine() ends the row after both inner loops finish.

Break
=

Right-aligned triangle complete

Total numbers = n(n+1)/2O(n²) time, O(1) extra memory.

🔎 Worked Walkthrough — rows = 5, row i = 3

Trace row 3 — space count, numbers printed, and full row output.

StepDetailOutput so far
Space loopj = 5, 4 — two spaces
k = 1{0,2} prints 11
k = 2{0,2} prints 21 2
k = 3{0,2} prints 31 2 3
WriteLineEnd row 31 2 3

Space count per row = rows - i. Numbers per row = i. Total prints = n(n+1)/2 for n rows.

Use Cases

Where this tiny pattern (and its loop structure) shows up beyond the homework prompt.

1. Teaching Nested Loops

Clearest visual proof that outer and inner bounds interact.

Example: remove the space loop and watch the triangle snap left.

2. Pattern Series Base

Foundation for right-aligned variants with separate space and number loops.

Example: compare with Program 42 (hollow square) and Program 44 next.

3. Console Formatting Drills

Practice {0,2} formatting and fixed-width columns.

Example: change {0,2} to {0,3} for wider spacing on large row counts.

4. Padding character

Add leading spaces once the three-loop structure works.

Example: loop k from i down to 1 for a descending row variant.

5. Complexity Intuition

Triangular totals make O(n²) concrete for beginners.

Example: count printed numbers for rows = 5 — total is 1+2+3+4+5 = 15.

6. Input Validation Labs

Pair the pattern with TryParse and positive-row checks.

Example: reject rows <= 0 and re-prompt.

Pro Tip: when an interviewer asks for patterns, explain the outer/inner roles first — then write the loops. The story matters as much as the code.

Advantages

Why this pattern earns a permanent spot in beginner C# courses.

  1. 1. Instant Visual Feedback

    Wrong bounds show up immediately as a broken staircase.

  2. 2. Minimal Concepts

    Only loops and console output — no arrays or math libraries.

  3. 3. Easy to Extend

    Invert, center, hollow, or change the fill character with small edits.

  4. 4. O(1) Extra Memory

    Streaming output needs no storage beyond loop counters.

Pro Tip: trace i, the space loop, and the number loop on paper for rows = 3 before coding — watch how the space count shrinks each row.

Usage Tips

Small habits that keep number-pattern code clean.

  1. 1. Two Inner Loops

    Space loop (j > i) and number loop (k = 1..i) must run in order before WriteLine().

  2. 2. Prefer TryParse

    Avoid crashes when the user types letters instead of a number.

  3. 3. Keep WriteLine Outside

    Only call WriteLine() after the inner loop finishes the row.

  4. 4. Trace 1..i on Paper

    Write the ascending sequence 1..i on paper before coding the number loop.

  5. 5. Dry-Run rows = 3

    Trace i = 1..3 on paper before coding the full rows = 5 demo.

Pro Tip: if the output is a vertical list of single digits per line, you almost certainly put WriteLine inside the inner loop.

Common Pitfalls

Mistakes that commonly break right-aligned number triangles.

  1. 1. WriteLine Inside the Inner Loop

    Each digit lands on its own line — you get a column, not a triangle.

    → Use Write("{0,2}", k); WriteLine only after both inner loops.

  2. 2. Skipping the Space Loop

    Without for (j = rows; j > i; j--), every row starts at the left margin.

    → Run the space loop before the number loop on every row.

  3. 3. Field Width Too Small

    {0,2} works for rows up to 9; larger counts need {0,3} or wider.

    → Match the format width to the largest digit you will print.

  4. 4. Skipping {0,2}

    Plain Write(k) makes multi-digit values crowd earlier columns.

    → Use Console.Write("{0,2}", k) for consistent column width.

  5. 5. Blind Convert.ToInt32

    Letters or empty input throw FormatException.

    → Prefer int.TryParse and re-prompt on failure.

Edge Cases

Check these inputs before calling the solution done.

rows = 1

Single row

Output is just 1 on one line — no leading spaces when rows = 1.

rows = 0

Empty pattern

Outer loop never runs when rows < 1 — print nothing or show a message.

Negative

rows < 1

Treat as invalid; re-prompt instead of silent empty output.

rows = 2

Smallest triangle

Two rows: 1 and 1 2.

Bad input

Non-numeric ReadLine

Convert.ToInt32 throws — use TryParse.

Large rows

Large row count

Total numbers = rows(rows+1)/2 — grows quadratically with rows.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Hollow square

  • Review Program 42
  • Compare grid border logic with triangle indentation

2. Next in series

  • Continue with Program 44
  • Next pattern in the number-pattern series

3. Sequence trace

  • Prove on paper: row i prints 1 to i
  • Space count = rows - i

4. Safe input loop

  • Use TryParse until rows >= 1
  • Then draw the triangle

Notes

  • Loop rule. Outer i = 1..rows. Space loop j = rows..i+1 prints one space. Number loop k = 1..i prints {0,2}.
  • Console.Write stays on the line; WriteLine advances — mix them carefully.
  • Validate rows >= 1 for interactive programs; rows = 1 prints a single 1.
  • Space count = rows - i — compare with Example 3 where removing the space loop gives a left-aligned triangle.

Quick Takeaway: outer i = 1..rows, space loop j = rows..i+1, numbers k = 1..i with {0,2}, then WriteLine().

⏱️ Time and Space Complexity

ProgramTimeExtra space
Nested loops (Examples 1–3)O(n²)O(1)
Smaller demo (Example 3)O(n²)O(1)
Wrap Up

🎉 Conclusion

The right-aligned number triangle is a compact lesson in dual inner loops and formatted output: print spaces while j > i, print 1..i with {0,2}, and end each row with WriteLine(). Master the fixed-rows version, then try user input and the left-aligned contrast.

Practice the three examples above, then continue to Program 44 for the next pattern in the series.

Run the space loop before the number loop — validate rows when reading from the console.

💡 Best Practices

✅ Do

  • Use for (i = 1; i <= rows; i++) in the outer loop
  • Spaces: for (j = rows; j > i; j--) Console.Write(" ");
  • Numbers: Console.Write("{0,2}", k) for k = 1..i
  • Prefer int.TryParse over bare Convert.ToInt32
  • State O(n²) time when asked about complexity

❌ Don’t

  • Call WriteLine inside an inner loop
  • Skip the space loop (breaks right alignment)
  • Use {0,1} when rows may exceed 9
  • Ignore bad console input in user-facing demos
  • Skip the rows = 1 edge case

Key Takeaways

Knowledge Unlocked

Five things to remember about this number triangle

Print the pattern the beginner-friendly way.

5
Core concepts
02

Space loop

j > i spaces

Code
0 03

{0,2}

Fixed width

Code
04

Row break

WriteLine after j

Shape
O 05

Complexity

O(n²) time

Analysis

❓ Frequently Asked Questions

A right-aligned ascending triangle: row 1 prints 1, row 2 prints 1 2, row 3 prints 1 2 3, and so on until 1 2 3 4 5.
Before printing numbers, the program prints spaces while j > i. Smaller rows get more spaces, pushing digits to the right edge.
The format specifier reserves 2 columns per number (right-aligned), keeping columns stable when values become two digits.
Remove the space loop that prints leading spaces. Then print numbers 1 to i directly — see Example 3.
Program 42 prints a hollow square grid with border conditions. Program 43 prints an ascending number triangle with indentation spaces.
Use a rows variable and loop i from 1 to rows — see Example 2.
O(n²) for n rows because total prints are 1 + 2 + ... + n = n(n+1)/2.
Prefer int.TryParse(Console.ReadLine(), out rows) so bad input does not throw FormatException.
Only one row prints — a single 1 with no leading spaces.

Did you Know? 🔊

Each row prints numbers 1 to i. A space loop runs while j > i before the number loop; {0,2} keeps columns aligned in the console.

Continue to Program 44

Move on to the next pattern in the C# number-pattern series.

Program 44 tutorial →

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.

12 people found this page helpful