Ascending Number Triangle in C#

What You’ll Learn
How to print an ascending number triangle in C# using nested for loops. Each row starts at 1 and prints up to the current row index: 1, 12, 123, and so on.
This pattern is a simple way to understand how the outer loop controls the number of rows and the inner loop controls how many digits appear on each row.
⭐ Pattern Output
For rows = 5, the pattern looks like this:
1
12
123
1234
12345Complete C# Program
The outer loop counts from 1 to rows. The inner loop prints numbers from 1 to the current row index.
using System;
namespace MyApp
{
class Program
{
static void Main(string[] args)
{
int rows = 5;
int i, j;
for (i = 1; i <= rows; i++)
{
for (j = 1; j <= i; j++)
{
Console.Write(j);
}
Console.WriteLine();
}
}
}
}🧠 How It Works
Set the number of rows
int rows = 5; sets the height of the triangle.
Outer loop (row control)
for (i = 1; i <= rows; i++) decides which row you are printing.
Inner loop (print 1..i)
for (j = 1; j <= i; j++) prints the digits for the current row.
New line
Console.WriteLine() moves to the next row after printing each line.
Ascending number triangle
Total prints are 1+2+…+n = n(n+1)/2, so time complexity is O(n²) for n rows.
Variation — User Input Version
Let the user choose the number of rows at runtime:
using System;
namespace MyApp
{
class Program
{
static void Main(string[] args)
{
Console.Write("Enter the number of rows: ");
int rows = Convert.ToInt32(Console.ReadLine());
for (int i = 1; i <= rows; i++)
{
for (int j = 1; j <= i; j++)
{
Console.Write(j);
}
Console.WriteLine();
}
}
}
}💡 Tips for Enhancement
Try These
- Validate input with
int.TryParsebefore converting - Add spacing with
Console.Write(j + " ") - Right-align the triangle by printing leading spaces before each row
- Print the row number repeatedly to create repeating-number patterns
Avoid
- Forgetting
Console.WriteLine()after each row - Using
Convert.ToInt32without handling invalid input - Putting the newline inside the inner loop (breaks the row)
Key Takeaways
The outer loop runs rows from 1 to rows.
The inner loop prints from 1 to the current row index i.
Total printed digits follow triangular numbers: n(n+1)/2.
The same loop idea helps build pyramids, Floyd’s triangle, and many other patterns.
❓ Frequently Asked Questions
i = 1, so the inner loop prints j from 1 to 1.rows to 1: for (i = rows; i >= 1; i--). Keep the inner loop printing 1..i.n(n+1)/2.Explore More C# Number Patterns!
Try inversions, alignments, and repeating digits to level up your nested-loop skills.
The total number of printed digits grows like a triangular number. If you print n rows, the total count is 1+2+…+n = n(n+1)/2.
12 people found this page helpful
