Alternating 1 and 0 Pattern in C#

Beginner
⏱️ 9 min read
📚 Updated: Aug 2026
🎯 3 Code Examples
🚀 Live Preview
Nested Loops + Modulo

What You’ll Learn

The alternating 1 and 0 pattern prints 11111, 0000, 111, 00, 1 — a natural step after Program 39’s rotating number pattern. This tutorial covers nested loops with i % 2 parity, shrinking row lengths, a live preview, algorithm steps, worked C# examples, edge cases, and complexity.

Shape Rule

1 or 0 per row

Row 1 prints 11111, row 2 prints 0000, row 3 prints 111 — odd rows use 1, even rows use 0.

Outer Loop

i = 1..rows

for (i = 1; i <= rows; i++) walks each row and drives the parity check.

Inner Loop

i..rows

for (j = i; j <= rows; j++) repeats the row character rows - i + 1 times.

Parity Check

i % 2

i % 2 == 0 prints 0; otherwise print 1 for the whole row.

Live Preview

3–9 rows

Pick a row count and draw the alternating binary triangle in the browser.

O(n²)

Complexity

Total character prints = n(n+1)/2; extra memory stays O(1).

Introduction

A alternating 1 and 0 pattern prints only 1 or 0 on each row, alternating by row parity while the row length shrinks. With rows = 5, the output is 11111, 0000, 111, 00, 1.

In C# the outer loop runs i = 1..rows, the inner loop repeats a character rows - i + 1 times, and i % 2 picks 1 or 0 for the whole row.

Why it matters?

It combines nested loops with a condition — a key step after Program 39’s rotating rows.

Key Highlights

Shrinking rows

Inner loop runs i..rows.

Parity rule

Odd i1; even i0.

vs Program 39

Program 39 rotates digits; Program 40 alternates binary symbols.

Series Foundation

Follow Program 39; continue to Program 41 next.

In short: outer i = 1..rows, inner j = i..rows, print 1 or 0 via i % 2, then WriteLine().

📝 Problem & Approach

Given a positive integer rows (e.g. 5), print an alternating binary triangle: odd rows are all 1s, even rows are all 0s, with row length decreasing from rows to 1.

C#
// rows = 5
//11111
//0000
//111
//00
//1

Inputs & Outputs

ItemTypeDescription
rowsintNumber of triangle lines; also controls the longest row width.
iintOuter loop — current row index; drives parity via i % 2.
jintInner loop — repeats the row character from i to rows.

Minimal workflow

Pseudocode
for i from 1 to rows:
    ch = "0" if i is even else "1"
    for j from i to rows:
        print ch
    print newline

Approach comparison

ApproachIdeaBest for
Nested loops + modulo11111, 0000, …Learning and interviews
User-input rowsint.TryParse(...)Flexible console programs
Spaced outputConsole.Write(ch + " ")Easier reading per row

⚡ Quick Reference

GoalPattern
Walk rowsfor (i = 1; i <= rows; i++)
Repeat row charfor (j = i; j <= rows; j++) Console.Write(ch);
Pick 1 or 0i % 2 == 0 ? "0" : "1"
End the rowConsole.WriteLine();
Spaced charsConsole.Write(ch + " ");
User inputint.TryParse(Console.ReadLine(), out rows)
Program 39 contrastRotating digits i..rows then i-1..1 — no modulo

📋 Fixed Rows vs User Input vs Spaced Output

Same alternating 1/0 triangle — different ways to control rows and formatting.

Outer loop
i = 1..rows

Walks each row

Inner loop
j = i..rows

Repeats row character

Parity
i % 2

Odd → 1, even → 0

Learning tip
j++

Inner loop counts up

Context

When This Pattern Shows Up

Reach for this pattern when teaching conditions inside nested loops and shrinking row lengths.

  1. Post Program 39 exercise

    Natural follow-up after Program 39 — same shrinking rows but each line is all 1s or all 0s.

  2. Nested-loop warm-up

    Outer/inner bound practice with an immediate visual check.

  3. Console I/O practice

    Combine loops with ReadLine for a flexible row count.

  4. Gateway to variants

    Compare Program 39 (rotating digits) and Program 41 (next in series) next.

  5. Not a UI layout tool

    This is a console teaching pattern — not how you build modern app screens.

Key benefit: one small program that locks in nested loops, output sequencing, and O(n²) thinking.

🔮 Live Preview

Choose a row count between 3 and 9 and draw the alternating 1/0 triangle in the browser.

Try 4, 5, or 7. Max up to 9 in this preview.

Live result
Press "Draw pattern".

Examples Gallery

Three complete C# programs — fixed rows, user input, and a smaller trace demo. Click View Output to reveal sample console results.

📚 Getting Started

Print five rows of the alternating 1/0 triangle with nested loops and modulo.

Example 1 — Fixed rows = 5

Hard-coded row count — ideal for first demos and screenshots.

C#
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

When i = 1 (odd), the inner loop prints 1 five times — output 11111. When i = 2 (even), it prints 0 four times — output 0000. The outer loop increases i each row, shortening the inner loop.

📈 User Input

Read the row count from the console instead of hard-coding 5.

Example 2 — User Input

Read rows from the console with safe parsing.

C#
using System;

namespace MyApp
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Enter the number of rows: ");
            if (!int.TryParse(Console.ReadLine(), out int rows) || rows < 1) return;

            for (int i = 1; i <= rows; i++)
            {
                for (int j = i; j <= rows; j++)
                    Console.Write(i % 2 == 0 ? "0" : "1");

                Console.WriteLine();
            }
        }
    }
}

How It Works

Same inner-loop core as Example 1; only the source of rows changes from a literal to user input.

⚡ Spaced Output

Add a space between characters for easier reading on each row.

Example 3 — Spaced Characters

Keep rows = 5 but print each character followed by a space.

C#
using System;

namespace MyApp
{
    class Program
    {
        static void Main(string[] args)
        {
            int rows = 5;

            for (int i = 1; i <= rows; i++)
            {
                string ch = (i % 2 == 0) ? "0" : "1";
                for (int j = i; j <= rows; j++)
                {
                    Console.Write(ch + " ");
                }
                Console.WriteLine();
            }
        }
    }
}

How It Works

Only the print statement changes — Console.Write(ch + " ") instead of Console.Write(ch). Loop bounds and parity check stay the same as Example 1.

🧠 How the Algorithm Prints Rows

1

Set up

using System; brings in Console. Set loop variables i, j with rows = 5.

Setup
2

Outer loop walks rows

for (i = 1; i <= rows; i++) — ascending outer loop walks each row.

Row
3

Inner loop (j)

for (j = i; j <= rows; j++) — repeats the row character rows - i + 1 times.

Repeat
4

Parity check

i % 2 == 0 prints 0; otherwise print 1 for the whole row.

Modulo
5

New line

Console.WriteLine() ends the row after the inner loop finishes.

Break
=

Alternating 1/0 triangle complete

Rows shrink from rows characters to one — O(n²) time, O(1) extra memory.

🔎 Worked Walkthrough — rows = 5

Trace each outer-loop value of i, the inner-loop range, character count, parity, and full row output.

iInner loop (j)CharPrintsRow output
11, 2, 3, 4, 51511111
22, 3, 4, 5040000
33, 4, 513111
44, 50200
55111

Prints per row = rows - i + 1 — total prints = n(n+1)/2 for n rows.

Use Cases

Where this tiny pattern (and its loop structure) shows up beyond the homework prompt.

1. Teaching Nested Loops

Clearest visual proof that outer and inner bounds interact.

Example: swap the if/else to start rows with 0 instead of 1.

2. Pattern Series Base

Foundation for inverted, pyramid, diamond, and hollow variants.

Example: continue to Program 41 for the next pattern in the series.

3. Console Formatting Drills

Practice Write vs WriteLine without complex math.

Example: put WriteLine inside the inner loop by mistake.

4. Spaced Output

Add spaces between characters once the two-loop structure works.

Example: use Console.Write(ch + " ") between characters on each row.

5. Complexity Intuition

Triangular totals make O(n²) concrete for beginners.

Example: count printed characters for rows = 5 — total is 15 (5+4+3+2+1).

6. Input Validation Labs

Pair the pattern with TryParse and positive-row checks.

Example: reject rows <= 0 and re-prompt.

Pro Tip: when an interviewer asks for patterns, explain the outer/inner roles first — then write the loops. The story matters as much as the code.

Advantages

Why this pattern earns a permanent spot in beginner C# courses.

  1. 1. Instant Visual Feedback

    Wrong bounds show up immediately as a broken staircase.

  2. 2. Minimal Concepts

    Only loops and console output — no arrays or math libraries.

  3. 3. Easy to Extend

    Invert, center, hollow, or change the fill character with small edits.

  4. 4. O(1) Extra Memory

    Streaming output needs no storage beyond loop counters.

Pro Tip: trace i and j on paper for rows = 3 before coding — watch how each row shortens by one character.

Usage Tips

Small habits that keep number-pattern code clean.

  1. 1. Match Loop Bounds

    Outer loop counts up (i++); inner loop counts from i to rows.

  2. 2. Prefer TryParse

    Avoid crashes when the user types letters instead of a number.

  3. 3. Keep WriteLine Outside

    Only call WriteLine() after the inner loop finishes the row.

  4. 4. Check Parity on i

    i % 2 == 0 picks 0 for even rows; odd rows print 1.

  5. 5. Dry-Run rows = 3

    Trace i = 1, 2, 3 on paper before coding the full rows = 5 demo.

Pro Tip: if the output is a vertical list of single characters per line, you almost certainly put WriteLine inside the inner loop.

Common Pitfalls

Mistakes that commonly break alternating 1/0 number triangles.

  1. 1. WriteLine Inside the Inner Loop

    Each character lands on its own line — you get a column, not a triangle.

    → Use Write(ch) for characters; WriteLine only after the inner loop.

  2. 2. Parity Inside Inner Loop

    Checking j % 2 alternates characters within a row — you get 10101, not a uniform row.

    → Check i % 2 once per row, outside or before the inner loop.

  3. 3. Wrong Inner Bounds

    for (j = 1; j <= i; j++) grows rows instead of shrinking them.

    → Use for (j = i; j <= rows; j++) so row i prints rows - i + 1 characters.

  4. 4. Inverted Parity

    Swapping odd/even by mistake starts with 0 on row 1 instead of 1.

    → Odd i prints 1: use i % 2 != 0 or else branch for 1.

  5. 5. Blind Convert.ToInt32

    Letters or empty input throw FormatException.

    → Prefer int.TryParse and re-prompt on failure.

Edge Cases

Check these inputs before calling the solution done.

rows = 1

Single character row

Output is just 1 on one line.

rows = 0

Empty pattern

Outer loop never runs — print nothing or show a message.

Negative

rows < 0

Treat as invalid; re-prompt instead of silent empty output.

rows = 2

Smallest triangle

Two rows: 11 and 0.

Bad input

Non-numeric ReadLine

Convert.ToInt32 throws — use TryParse.

Large rows

Large row count

Each row prints rows - i + 1 characters — total work grows as n(n+1)/2.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Rotating pattern

  • Review Program 39’s wrap-around rows
  • Compare with Program 39

2. Invert parity

  • Start with 0 on row 1 instead of 1
  • Swap the if/else outputs

3. Next in series

  • Continue with Program 41
  • Build on nested loops + conditions

4. Spaced output

  • Use Console.Write(ch + " ") between characters
  • Same loops, wider visual spacing

Notes

  • Loop rule. Outer loop: i = 1..rows. Inner loop: j = i..rows with j++. Parity: i % 2.
  • Console.Write stays on the line; WriteLine advances — mix them carefully.
  • Validate rows > 0 for interactive programs; rows = 1 should print a single 1.
  • Row i prints exactly rows - i + 1 characters — odd rows are 1, even rows are 0.

Quick Takeaway: outer loop i = 1..rows, inner loop j = i..rows, print 1 or 0 via i % 2, then WriteLine().

⏱️ Time and Space Complexity

ProgramTimeExtra space
Nested loops (Examples 1–3)O(n²)O(1)
Smaller demo (Example 3)O(n²)O(1)
Wrap Up

🎉 Conclusion

The alternating 1 and 0 pattern is a compact nested-loop lesson: an ascending outer loop shortens each row while i % 2 picks the row character. Master the fixed-rows version, then try user input and spaced output.

Practice the three examples above, then continue to Program 41 for the next pattern in the series.

Row i prints rows - i + 1 copies of 1 or 0 — keep WriteLine outside the inner loop and validate row counts when reading input.

💡 Best Practices

✅ Do

  • Use for (i = 1; i <= rows; i++) in the outer loop
  • Inner: for (j = i; j <= rows; j++) repeats the row character
  • Check i % 2 once per row to pick 1 or 0
  • Validate rows ≥ 1 for interactive programs
  • Prefer int.TryParse over bare Convert.ToInt32

❌ Don’t

  • Call WriteLine inside the inner character loop
  • Check j % 2 when you meant row parity on i
  • Use j = 1..i when rows should shrink
  • Ignore bad console input in user-facing demos
  • Skip the rows = 1 edge case

Key Takeaways

Knowledge Unlocked

Five things to remember about this alternating 1/0 triangle

Print the pattern the beginner-friendly way.

5
Core concepts
02

Outer loop

Counts up rows

Code
03

Inner loop

j = i up to rows

Code
04

Parity

i % 2 picks char

Modulo
O 05

Complexity

O(n²) time

Analysis

❓ Frequently Asked Questions

It checks i % 2. When i is even, the row prints 0; when i is odd, the row prints 1.
The inner loop runs from j = i to rows, printing rows - i + 1 characters per row — decreasing from rows down to 1.
Swap the if/else outputs, or invert the condition so odd rows print 0 and even rows print 1.
Program 39 rotates digits 1..rows per row. Program 40 prints only 1 or 0 per row based on parity, with shrinking row length.
Replace 5 with rows in the outer loop bound — see Example 2.
Use Console.Write(ch + " ") instead of Console.Write(ch) — see Example 3.
O(n²) for n rows because total prints are 1 + 2 + ... + n = n(n+1)/2.
Prefer int.TryParse(Console.ReadLine(), out rows) so bad input does not throw FormatException.
Only one row prints — a single 1 on one line.

Did you Know? 🔊

Odd rows print 1, even rows print 0 — chosen with i % 2. Row i prints rows - i + 1 characters; total prints = n(n+1)/2.

Continue to Program 41

Move on to the next pattern in the C# number-pattern series.

Program 41 tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

12 people found this page helpful