Alternating Binary Number Triangle in C#

What You’ll Learn
How to print an alternating binary number triangle in C#. Each row grows by one digit, and the digits alternate using % 2: 1, 01, 101, 0101, 10101.
This is a simple way to practice nested loops and understand how the modulo operator works.
⭐ Pattern Output
For rows = 5, the pattern looks like this:
1
01
101
0101
10101Complete C# Program
The outer loop controls the row length. The inner loop prints j % 2 while counting down from i to 1.
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 = i; j >= 1; j--)
{
Console.Write(j % 2);
}
Console.WriteLine();
}
}
}
}🧠 How It Works
Set the number of rows
int rows = 5; sets how many lines the pattern prints.
Outer loop (row length)
for (i = 1; i <= rows; i++) makes each next row one digit longer.
Inner loop (alternate 0/1)
j % 2 produces 0 for even j and 1 for odd j, which creates the alternating binary digits.
Alternating binary triangle
You print 1+2+…+n digits overall, so complexity is O(n²).
Variation — Start with 0
If you want the first row to be 0, flip the printed value:
using System;
namespace MyApp
{
class Program
{
static void Main(string[] args)
{
int rows = 5;
for (int i = 1; i <= rows; i++)
{
for (int j = i; j >= 1; j--)
{
Console.Write(1 - (j % 2));
}
Console.WriteLine();
}
}
}
}💡 Tips for Enhancement
Try These
- Read
rowsfrom the console to scale the pattern - Add spaces between digits to improve readability
- Use
(i + j) % 2to alternate by row + column parity
Avoid
- Forgetting the newline after each row
- Using string concatenation in tight loops (unnecessary here)
Key Takeaways
j % 2 produces alternating 0 and 1.
The inner loop direction changes the row’s visual ordering.
This is a simple example of using modulo to build patterns.
Overall complexity is \(O(n^2)\) for \(n\) rows.
❓ Frequently Asked Questions
j = 3, 2, 1 and j % 2 becomes 1, 0, 1.(col % 2) or ((col + row) % 2) depending on the style you want.Explore More C# Number Patterns!
Modulo-based patterns are a fun way to practice parity, loops, and condition-like behavior.
The modulo operator is used in many places: alternating patterns, checking even/odd numbers, hashing, and circular indexing.
12 people found this page helpful
