Alternating 1 and 0 Pattern in C#

What You’ll Learn
How to print a pattern where each row contains only 1 or 0, alternating by row, while the row length decreases from rows down to 1.
This is a simple exercise to practice nested loops and the modulo operator (%).
⭐ Pattern Output
For rows = 5, the pattern looks like this:
11111
0000
111
00
1Complete C# Program
Use i % 2 to decide whether to print 1 or 0 for the entire row.
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 <= rows; j++)
{
if (i % 2 == 0)
Console.Write("0");
else
Console.Write("1");
}
Console.WriteLine();
}
}
}
}🧠 How It Works
Outer loop (rows)
i runs from 1 to rows.
Inner loop (decreasing length)
for (j = i; j <= rows; j++) prints rows-i+1 characters.
Choose 1 or 0 using modulo
If i % 2 == 0 (even row), print 0. Otherwise print 1.
Alternating rows
Total printed characters are triangular: n(n+1)/2 \(\Rightarrow\) O(n²).
Variation — User Input Rows
Let the user choose the number of rows at runtime.
using System;
namespace MyApp
{
class Program
{
static void Main(string[] args)
{
int rows;
int i, j;
Console.Write("Enter number of rows: ");
if (!int.TryParse(Console.ReadLine(), out rows) || rows <= 0)
{
Console.WriteLine("Please enter a positive integer.");
return;
}
for (i = 1; i <= rows; i++)
{
for (j = i; j <= rows; j++)
Console.Write(i % 2 == 0 ? "0" : "1");
Console.WriteLine();
}
}
}
}💡 Tips for Enhancement
Try These
- Swap the outputs to start with 0s instead of 1s
- Print increasing length by changing the inner loop to run up to
i - Add spaces between digits if you want a more readable look
Avoid
- Forgetting to print a newline after each row
- Using invalid row counts without validation
Key Takeaways
Odd rows print 1, even rows print 0.
Row length decreases because inner loop prints rows-i+1 characters.
The modulo operator (%) is a simple way to check parity.
Total prints are triangular \(\Rightarrow\) O(n²).
Explore More C# Number Patterns!
Alternating patterns are a great way to practice conditions inside loops.
Parity checks like i % 2 are commonly used in pattern problems to alternate symbols, numbers, or colors row by row.
12 people found this page helpful
