Alternating 1 and 0 Pattern with Decreasing Width in PHP

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

What You’ll Learn

The alternating 1/0 pattern repeats one digit per row while the width shrinks. Odd rows print 1, even rows print 0. This tutorial covers the parity rule, nested loops, a live preview, algorithm steps, worked PHP examples, edge cases, and complexity.

Shape Rule

Alternating 1/0, shrinking width

Odd rows print 1, even rows print 0; each row is one digit repeated.

Parity Rule

$i % 2

if ($i % 2 == 0) prints 0; otherwise print 1 on every inner iteration.

Width Loop

$j = $i..$rows

for ($j = $i; $j <= $rows; $j++) controls width — $rows - $i + 1 repeats per row.

Outer Loop

Row index i

for ($i = 1; $i <= $rows; $i++) walks each row and sets parity.

Live Preview

1–20 rows

Pick a row count and draw the alternating 1/0 pattern instantly in the browser.

O(n²)

Complexity

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

Introduction

An alternating 1/0 pattern repeats one digit per row while the line gets shorter. With $rows = 5, the output is 11111, 0000, 111, 00, and 1.

In PHP you use one outer loop for row parity ($i % 2) and one inner loop from $j = $i to $rows to control width, then call echo PHP_EOL after each row.

Why it matters?

It combines a simple parity check with shrinking inner-loop bounds — a common interview building block.

Key Highlights

Odd/Even Rows

Odd rows: 1; even rows: 0 via $i % 2.

Shrinking Width

Each row prints $rows - $i + 1 copies of the chosen digit.

Same Digit Per Row

echo the digit in the inner loop; echo PHP_EOL after.

Series Foundation

Follow Program 39 rotating pattern; continue to Program 41 square pyramid.

In short: for each row $i from 1 to $rows, print 1 or 0 based on $i % 2, repeat $rows - $i + 1 times, then call echo PHP_EOL.

📝 Problem & Approach

Given a positive integer $rows (e.g. 5), print an alternating 1/0 triangle where odd rows repeat 1 and even rows repeat 0, with width $rows - $i + 1 on row $i.

PHP
// $rows = 5
//11111
//0000
//111
//00
//1

Inputs & Outputs

ItemTypeDescription
$rowsintNumber of triangle lines to print (typically ≥ 1).
Printed outputtextLeft-aligned rows of repeated 1 or 0; row $i has $rows - $i + 1 characters.

Minimal workflow

Pseudocode
for i from 1 to rows:
    pick digit = 1 if i is odd else 0
    for j from i to rows:
        print digit
    print newline

Approach comparison

ApproachIdeaBest for
Parity + nested loops11111, 0000, …Learning and interviews
User-input rowstrim(fgets(STDIN));Flexible console programs
Spaced outputecho ($i % 2 == 0 ? "0" : "1") . " "Easier reading per row

⚡ Quick Reference

GoalPattern
Walk each rowfor ($i = 1; $i <= $rows; $i++)
Pick digit by parityif ($i % 2 == 0) echo "0"; else echo "1";
Control row widthfor ($j = $i; $j <= $rows; $j++)
End the rowecho PHP_EOL;
Program 39 contrastRotation uses two inner loops; this pattern uses parity + one inner loop

📋 Parity vs Width vs Combined

Same alternating row — how parity and the inner loop work together.

Parity (row)
$i % 2

Odd rows print 1; even rows print 0

Width (inner)
$j = $i..$rows

Repeats the digit $rows - $i + 1 times

Row length
shrinks

Row $i has exactly $rows - $i + 1 characters

Learning tip
trace i=2

Dry-run row 2: even parity, inner loop 2..5 → four zeros

Context

When This Pattern Shows Up

Reach for this pattern when teaching parity check and one inner loop on the same row.

  1. First lab exercise

    Most PHP pattern series start here before pyramids and diamonds.

  2. Nested-loop warm-up

    Outer/inner bound practice with an immediate visual check.

  3. Console I/O practice

    Combine loops with fgets(STDIN) for a flexible row count.

  4. Gateway to variants

    Compare with Program 39 (rotating), then continue to Program 41 (square pyramid).

  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 1 and 20 and draw the alternating 1/0 pattern in the browser.

Try 5, 7, or 10. Larger values still work up to 20.

Live result
Press "Draw pattern".

Examples Gallery

Three complete PHP programs — fixed row count, fgets(STDIN) input, and a spaced-output variant. Click View Output to reveal sample console results.

📚 Getting Started

Print five rows with parity check and nested loops per line.

Example 1 — Fixed $rows = 5

Hard-coded size — parity check and one inner loop build each alternating row.

PHP
<?php
$rows = 5;

for ($i = 1; $i <= $rows; $i++) {
    for ($j = $i; $j <= $rows; $j++) {
        if ($i % 2 == 0) {
            echo "0";
        } else {
            echo "1";
        }
    }
    echo PHP_EOL;
}

How It Works

When $i = 1, the inner loop runs 5 times and prints 1 each time — output 11111. When $i = 2, it runs 4 times with even parity — output 0000.

📈 Practical Variant

Let the user choose the height at runtime.

Example 2 — User Input Version

Read the row count with trim(fgets(STDIN)) (check is_numeric() in real apps).

PHP
<?php
echo "Enter the number of rows: ";
$input = trim(fgets(STDIN));
if (!is_numeric($input)) {
    echo "Invalid input." . PHP_EOL;
    exit(1);
}
$rows = (int) $input;

for ($i = 1; $i <= $rows; $i++) {
    for ($j = $i; $j <= $rows; $j++) {
        echo ($i % 2 == 0 ? "0" : "1");
    }
    echo PHP_EOL;
}

How It Works

Same nested-loop core as Example 1; only the source of $rows changes. Non-numeric input fails is_numeric() — validate before casting to int for safer labs.

⚡ Readability Variant

Same alternating rows with spaces between digits for easier reading.

Example 3 — Spaced Output

Append a space after each repeated digit for easier reading.

PHP
<?php
$rows = 5;

for ($i = 1; $i <= $rows; $i++) {
    for ($j = $i; $j <= $rows; $j++) {
        echo ($i % 2 == 0 ? "0" : "1") . " ";
    }
    echo PHP_EOL;
}

How It Works

Same loop structure; only the print calls add + " " after each repeated digit.

🧠 How the Algorithm Prints Rows

1

Set up

Set $rows = 5; and use fgets(STDIN) when reading input. Set loop variables $i, $j.

Setup
2

Outer loop (rows)

for ($i = 1; $i <= $rows; $i++) walks each row and sets parity via $i % 2.

Row
3

Inner loop (width)

for ($j = $i; $j <= $rows; $j++) repeats the chosen digit $rows - $i + 1 times.

Width
4

Parity pick (1 or 0)

If $i % 2 == 0 print 0; else print 1, then echo PHP_EOL ends the row.

Parity
=

Alternating triangle complete

Total digit prints: n(n+1)/2O(n²) time, O(1) extra memory.

🔎 Worked Walkthrough — $rows = 5

Trace each row: parity pick, inner-loop range, width, and full row output.

$iParityInner loop (j)WidthRow output
1odd1..5511111
2even2..540000
3odd3..53111
4even4..5200
5odd5..511

Total character prints: 5+4+3+2+1 = 15 = n(n+1)/2.

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: change j <= i and watch the shape change.

2. Pattern Series Base

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

Example: change k start to 100 for a shifted sequence.

3. Console Formatting Drills

Practice echo vs echo PHP_EOL without complex math.

Example: put echo PHP_EOL inside the inner loop by mistake.

4. Character Substitution

Swap digits for letters, stars, or spaced output once the loop works.

Example: use %4d when values exceed two digits.

5. Complexity Intuition

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

Example: count printed digits for n = 10 still → 55.

6. Input Validation Labs

Pair the pattern with fgets(STDIN) 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 PHP 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: learn the parity + width version first; then try spaced output for a grid-like view.

Usage Tips

Small habits that keep number-pattern code clean.

  1. 1. Name Bounds Clearly

    Use $rows (or $n) and keep $i/$j for loops — or rename to $row/$col.

  2. 2. Prefer fgets(STDIN)

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

  3. 3. Keep echo PHP_EOL Outside

    Only call echo PHP_EOL after the inner loop finishes the row.

  4. 4. Use Ternary for Parity

    echo ($i % 2 == 0 ? "0" : "1"); keeps the inner loop compact.

  5. 5. Dry-Run One Small n

    Trace $rows = 3 on paper before coding larger demos.

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

Common Pitfalls

Mistakes that commonly break alternating 1/0 patterns.

  1. 1. echo PHP_EOL Inside the Inner Loop

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

    → Use echo for the digit; echo PHP_EOL only after the inner loop.

  2. 2. Wrong Inner Bound

    for ($j = 1; $j <= $i; $j++) grows width instead of shrinking — you get a different triangle shape.

    → Keep for ($j = $i; $j <= $rows; $j++) so each row shortens by one character.

  3. 3. Forgetting the Row Break

    Omitting echo PHP_EOL glues every digit onto one endless line.

    → Always end the row after the inner loop.

  4. 4. Unchecked STDIN input

    Letters or empty input leave $rows uninitialized.

    → Prefer fgets(STDIN) and re-prompt on failure.

  5. 5. Flipped Parity Check

    Checking $j % 2 instead of $i % 2 alternates digits within a row instead of between rows.

    → Base parity on the outer index $i, not the inner counter $j.

Edge Cases

Check these inputs before calling the solution done.

$rows = 1

Single digit

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.

Large n

Many rows

Output grows as n²/2 characters — fine for labs, noisy for huge n.

Bad input

Non-numeric STDIN input

Unchecked fgets(STDIN) leaves $rows unset — call is_numeric($input) first.

Fill char

Flip start digit

Swap the if/else branches to start with 0 on row 1.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Rotating number pattern

2. Square number pyramid

  • Centered pyramid of squared values
  • Continue with Program 41

3. Flip parity

  • Start with 0 on odd rows instead of 1
  • Same loops, swapped if/else branches

4. Spaced output

  • Add spaces between digits for rows > 9
  • See Example 3 on this page

Notes

  • Character count. Total prints for n rows is n(n+1)/2 — row $i contributes $rows - $i + 1 characters.
  • print stays on the line; println advances — mix them carefully.
  • Validate $rows > 0 for interactive programs; $rows = 1 should print a single 1.
  • Odd rows always print 1; even rows print 0 — flip the branches to reverse the start digit.

Quick Takeaway: outer loop sets parity with $i % 2, inner loop $j = $i..$rows repeats the digit, then break the line.

⏱️ Time and Space Complexity

ProgramTimeExtra space
Nested loops (Examples 1–2)O(rows²)O(1)
Spaced output (Example 3)O(rows²)O(1)
Wrap Up

🎉 Conclusion

The alternating 1/0 pattern combines one outer loop with parity check and one inner loop per row — a natural step after rotating patterns. Master the compact digit output first, then optionally add spaces for readability.

Practice the three examples above, then continue to Program 41 for the square number pyramid.

Row $i prints one digit repeated $rows - $i + 1 times — keep echo PHP_EOL only after the inner loop finishes.

💡 Best Practices

✅ Do

  • Explain parity ($i % 2) and inner bounds before coding
  • Use echo in the inner loop and echo PHP_EOL after each row
  • Validate $rows ≥ 1 for interactive programs
  • Check is_numeric($input) before using $rows
  • State O(n²) time when asked about complexity

❌ Don’t

  • Call echo PHP_EOL inside the inner digit loop
  • Check parity on $j instead of $i (alternates within a row)
  • Use $j = 1..$i when you meant shrinking width
  • 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 pattern

Print the pattern the beginner-friendly way.

5
Core concepts
02

Outer loop

Sets row parity

Code
03

Inner loop

$j = $i..$rows width

Logic
04

Shrinking width

$rows - $i + 1 chars

I/O
O 05

Complexity

O(n²) time

Analysis

❓ Frequently Asked Questions

The code checks $i % 2. When $i is even it prints 0; otherwise it prints 1.
The inner loop runs from $j = $i to $rows, which is $rows - $i + 1 iterations — one fewer character each row.
Yes. Swap the digits in the if/else, or flip the parity check to print 0 on odd rows and 1 on even rows.
Program 39 rotates digits 12345, 23451, etc. Program 40 repeats a single digit per row and alternates 1/0 based on row parity.
Yes. Print "1 " and "0 " in the inner loop — see Example 3.
O(n²) for n rows because total printed characters are n + (n-1) + ... + 1 = n(n+1)/2.
Use trim(fgets(STDIN)) and check is_numeric($input) before casting to int.
The outer loop never runs, so nothing is printed. Validate and prompt again if you want a clear user message.

Did you Know? 🔊

Each row prints the same digit repeatedly — 1 on odd rows and 0 on even rows. The inner loop runs from $j = $i to $rows, so width is $rows - $i + 1 and shrinks each line.

Continue to Program 41

Move on to the square number pyramid in the PHP 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