Alternating Binary Number Triangle (Starting with 1) in C#

What You’ll Learn
How to print an alternating binary number triangle in C# where each row starts with 1 and alternates: 1, 10, 101, 1010, 10101.
The trick is printing j % 2 while j counts from 1 upward on each row.
⭐ Pattern Output
For rows = 5, the pattern looks like this:
1
10
101
1010
10101Complete C# Program
The outer loop controls the number of rows. The inner loop prints j % 2 from j = 1 to j = i.
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 % 2);
}
Console.WriteLine();
}
}
}
}🧠 How It Works
Set the size
rows decides how many lines to print.
Outer loop (row length grows)
i increases from 1 to rows, so each row prints one extra digit.
Inner loop (print j%2)
As j goes 1, 2, 3, ... the expression j % 2 prints 1, 0, 1, 0, ...
Alternating binary pattern
Total prints are triangular: n(n+1)/2, so time complexity is O(n²).
Variation — Start with 0
If you want rows to start with 0 instead of 1, flip the output:
using System;
namespace MyApp
{
class Program
{
static void Main(string[] args)
{
int rows = 5;
for (int i = 1; i <= rows; i++)
{
for (int j = 1; j <= i; j++)
{
Console.Write(1 - (j % 2));
}
Console.WriteLine();
}
}
}
}💡 Tips for Enhancement
Try These
- Read
rowsfrom the console to scale the pattern - Alternate by row+column with
(i + j) % 2 - Add spaces between digits for readability
Avoid
- Forgetting the newline after each row
- Using string concatenation inside the loops
Key Takeaways
j % 2 alternates between 1 and 0 as j increments.
The outer loop controls how many digits each row prints.
This pattern is a quick exercise for modulo + nested loops.
Overall complexity is \(O(n^2)\) for \(n\) rows.
❓ Frequently Asked Questions
j % 2 prints 1 then 0.n(n+1)/2.Explore More C# Number Patterns!
Try switching the loop direction or using row+column parity to create even more binary patterns.
Alternating 0/1 patterns are closely related to parity checks, checkerboards, and XOR logic.
12 people found this page helpful
