Alternating Zigzag Number Triangle in C#

What You’ll Learn
How to print an alternating zigzag number triangle in C#. Odd-length rows print numbers in ascending order (12345, 123, 1), while even-length rows print numbers in descending order (4321, 21).
This example combines nested loops with an if/else condition to switch the direction per row.
⭐ Pattern Output
For rows = 5, the pattern looks like this:
12345
4321
123
21
1Complete C# Program
The outer loop decreases the row length. For even i, print i..1; for odd i, print 1..i.
using System;
namespace MyApp
{
class Program
{
static void Main(string[] args)
{
int rows = 5;
int i, j;
for (i = rows; i >= 1; i--)
{
if (i % 2 == 0)
{
for (j = i; j >= 1; j--)
{
Console.Write(j);
}
}
else
{
for (j = 1; j <= i; j++)
{
Console.Write(j);
}
}
Console.WriteLine();
}
}
}
}🧠 How It Works
Set the row count
int rows = 5; defines the first (longest) row.
Outer loop (shrink the row)
for (i = rows; i >= 1; i--) controls how many digits each row contains.
Branch on parity
If i is even, print in reverse; if odd, print forward.
End the row
Console.WriteLine() moves to the next row.
Zigzag direction
You still print 5+4+3+2+1 digits in total, so complexity is O(n²).
Variation — User Input Version
Read the number of rows and apply the same zigzag logic:
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 = rows; i >= 1; i--)
{
if (i % 2 == 0)
{
for (int j = i; j >= 1; j--)
{
Console.Write(j);
}
}
else
{
for (int j = 1; j <= i; j++)
{
Console.Write(j);
}
}
Console.WriteLine();
}
}
}
}💡 Tips for Enhancement
Try These
- Validate input with
int.TryParsebefore converting - Add spaces between digits for readability
- Flip the parity rule (odd rows reverse, even rows forward)
- Use the same idea to alternate between numbers and symbols
Avoid
- Forgetting the newline after each row
- Mixing up your inner-loop direction
- Using
%without understanding even/odd parity
Key Takeaways
Use i % 2 to switch direction between rows.
Odd rows print 1..i; even rows print i..1.
The outer loop controls row length from rows down to 1.
Overall complexity is still \(O(n^2)\).
❓ Frequently Asked Questions
i = 4 (even), so the code prints from 4 down to 1.rows (or read it from the console) and the same logic will scale.n(n+1)/2 digits overall.Explore More C# Number Patterns!
Alternating direction is a neat trick you can reuse in many pattern-printing problems.
Zigzag patterns are a simple introduction to using conditions inside loops—a stepping stone to more complex logic problems.
12 people found this page helpful
