Alternating Binary Number Triangle Pattern in PHP

Beginner
⏱️ 8 min read
📚 Updated: Aug 2026
🎯 3 Code Examples
🚀 Live Preview
Modulo Operator

What You’ll Learn

The alternating binary number triangle combines nested loops with the modulo operator to print 0 and 1 in an alternating sequence. This tutorial covers the shape rule, loop structure, a live preview, algorithm steps, worked PHP examples, edge cases, and complexity.

Shape Rule

j % 2 alternates 0 and 1

Row 1 prints 1, row 2 prints 01, row 3 prints 101, and so on as width grows.

Outer Loop

Rows

for ($i = 1; $i <= $rows; $i++) makes each new row one digit longer than the previous.

Inner Loop

i..1 descending

for ($j = $i; $j >= 1; $j--) prints $j % 2 while counting down, creating the alternating binary row.

echo vs PHP_EOL

Same line / next line

Binary digits use echo $j % 2; end each row with echo PHP_EOL.

Live Preview

1–20 rows

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

O(n²)

Complexity

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

Introduction

An alternating binary number triangle grows each row by one digit while alternating between 0 and 1 using the modulo operator. With rows = 5, the output is 1, 01, 101, 0101, 10101.

In PHP you solve it with an ascending outer loop and a descending inner loop: for ($j = $i; $j >= 1; $j--) prints $j % 2, then echo PHP_EOL; ends each row.

Why it matters?

It is a fun way to practice parity and nested loops before more complex logic-heavy patterns.

Key Highlights

Modulo Alternation

j % 2 yields 0 for even j, 1 for odd j.

Descending Inner Loop

j = i down to 1 sets digit order on each row.

Print Then Break

echo $j % 2 in the inner loop; echo PHP_EOL after.

Series Foundation

Follow Program 14; continue to Program 16 (ascending inner loop).

In short: for each row i from 1 to rows, print j % 2 for j from i down to 1, then call echo PHP_EOL.

📝 Problem & Approach

Given a positive integer rows, print an alternating binary number triangle: row i has i digits from j % 2 as j counts down from i to 1.

PHP
// rows = 5 (conceptual shape)
// 1
// 01
// 101
// 0101
// 10101

Inputs & Outputs

ItemTypeDescription
rowsintNumber of triangle lines to print (typically ≥ 1).
Printed outputtextEach row has i alternating binary digits from j % 2.

Minimal workflow

Pseudocode
for i from 1 to rows:
    for j from i down to 1:
        print j % 2 (no newline)
    print newline

Approach comparison

ApproachIdeaBest for
Descending inner + j % 21, 01, 101, …Learning and interviews
Flip with 1 - (j % 2)Start rows with 0 instead of 1Parity inversion variant

⚡ Quick Reference

GoalPattern
Walk each rowfor ($i = 1; $i <= $rows; $i++)
Print binary digitfor ($j = $i; $j >= 1; $j--) echo $j % 2;
End the rowecho PHP_EOL;
Flip parityecho 1 - ($j % 2);
Program 16 variantfor ($j = 1; $j <= $i; $j++) echo $j % 2 (ascending inner)
Row + column parityecho ($i + $j) % 2;

📋 j % 2 vs Flip vs Ascending Inner

Same binary triangle family — different ways to emit 0 and 1.

j % 2
parity

Even j → 0, odd j → 1

1 - (j % 2)
flipped

Inverts every digit — row 1 starts with 0

j down to 1
desc inner

This page — produces 1, 01, 101, …

Learning tip
% 2 first

Master j % 2 before row+column parity

Context

When This Pattern Shows Up

Reach for this pattern when teaching the modulo operator inside nested loops.

  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 Program 14 (odd-length rows) and Program 16 (ascending inner loop) 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 1 and 20 and draw the alternating binary triangle 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 rows, a flip variant, and a user-input version. Click View Output to reveal sample console results.

📚 Getting Started

Print five rows of the alternating binary triangle with j % 2.

Example 1 — Fixed rows = 5

Hard-coded height — ideal for first demos and screenshots.

PHP
<?php
$rows = 5;

for ($i = 1; $i <= $rows; $i++) {
    for ($j = $i; $j >= 1; $j--) {
        echo $j % 2;
    }
    echo PHP_EOL;
}

How It Works

When i = 1, the inner loop prints 1 % 2 = 1. When i = 3, it prints 3%2=1, 2%2=0, 1%2=1 as 101, and so on as row width grows. echo PHP_EOL after the inner loop starts the next row.

📈 Flip Variant

Invert parity so the first row starts with 0 instead of 1.

Example 2 — Flip with 1 - (j % 2)

Start each row with 0 instead of 1 by inverting the parity output.

PHP
<?php
$rows = 5;

for ($i = 1; $i <= $rows; $i++) {
    for ($j = $i; $j >= 1; $j--) {
        echo 1 - ($j % 2);
    }
    echo PHP_EOL;
}

How It Works

1 - (j % 2) flips every digit: where j % 2 was 1 it prints 0, and vice versa. Row 1 becomes 0 instead of 1.

⚡ User Input

Read the row count at runtime and scale the binary triangle.

Example 3 — User Input Version

Read $rows with (int) trim(fgets(STDIN)) and apply the same $j % 2 logic.

PHP
<?php
echo "Enter the number of rows: ";
$rows = (int) trim(fgets(STDIN));

for ($i = 1; $i <= $rows; $i++) {
    for ($j = $i; $j >= 1; $j--) {
        echo $j % 2;
    }
    echo PHP_EOL;
}

How It Works

Same nested-loop core as Example 1; only the source of rows changes. Non-numeric input leaves rows unset if you skip is_numeric() checks — always check it in safer labs.

🧠 How the Algorithm Prints Rows

1

Set up

Set $rows = 5; and use fgets(STDIN) when reading input. Set rows (fixed or from input).

Setup
2

Outer loop (row length)

for ($i = 1; $i <= $rows; $i++) makes each row one digit longer than the previous.

Row
3

Inner loop (modulo)

for ($j = $i; $j >= 1; $j--) prints $j % 2 with echo to alternate 0 and 1.

Binary
4

New line

echo PHP_EOL ends the row so the next outer iteration starts fresh.

Break
=

Binary triangle complete

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

🔎 Worked Walkthrough — rows = 4

Trace each outer-loop value of i and note the j % 2 values printed on each row.

iInner j orderj % 2 valuesPrinted row
1111
22, 10, 101
33, 2, 11, 0, 1101
44, 3, 2, 10, 1, 0, 10101

Total digit prints: 1 + 2 + 3 + 4 = 10 = 4×5/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: use (i + j) % 2 for row+column parity grids.

3. Console Formatting Drills

Practice echo vs 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: print j + " " for spaced digits on each row.

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 is_numeric() checks 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: learn j % 2 first; compare with 1 - (j % 2) to flip every digit on each row.

Usage Tips

Small habits that keep number-pattern code clean.

  1. 1. Name Bounds Clearly

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

  2. 2. Validate CLI input

    Call is_numeric(trim($line)) so bad input does not leave rows uninitialized.

  3. 3. Keep echo PHP_EOL Outside

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

  4. 4. Trace j % 2 on Paper

    Write the j values and their modulo before coding — catches direction mistakes early.

  5. 5. Dry-Run One Small n

    Trace rows = 5 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 binary number patterns.

  1. 1. Newline Inside the Inner Loop

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

    → Use echo $j % 2 for binary digits; echo PHP_EOL only after the inner loop.

  2. 2. Wrong Inner Direction

    Counting j up instead of down changes row ordering (see Program 16).

    → For this shape, keep for ($j = $i; $j >= 1; $j--).

  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 CLI input

    Letters or empty input leave rows uninitialized.

    → Prefer is_numeric() and re-prompt on failure.

  5. 5. Off-by-One on 0-Based Loops

    Switching to i = 0 without adjusting the inner bound prints an empty first row or wrong counts.

    → If 0-based, print i with wrong inner bound (e.g. j <= i + 1).

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 CLI input

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

Fill char

Forgot modulo

echo $j prints 1,2,3… — use echo $j % 2 for binary output.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Odd-length descending triangle

  • Outer loop i -= 2 for odd widths only
  • Continue with Program 14

2. Ascending inner binary triangle

  • Inner loop j = 1 to i instead of down
  • Continue with Program 16

3. Flip parity

  • Use 1 - (j % 2) so row 1 starts with 0
  • Compare output with Example 2

4. Spaced binary output

  • Use echo $j % 2 between digits
  • Harder follow-up after this page

Notes

  • Triangular sum. Digit prints for rows 1+2+3+…+n still grow as O(n²) for n rows.
  • echo $j % 2 stays on the line; echo PHP_EOL advances — mix them carefully.
  • Validate rows > 0 for interactive programs; rows = 1 should print a single 1.
  • This page is left-aligned. Centered pyramids need leading spaces — covered later in the series.

Quick Takeaway: outer loop grows row length, inner loop prints j % 2 descending, then break the line.

⏱️ Time and Space Complexity

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

🎉 Conclusion

The alternating binary number triangle is a compact lesson in modulo inside nested loops. Master the j % 2 version, then try the flip variant with 1 - (j % 2).

Practice the three examples above, then continue to Program 16 for the ascending-inner-loop binary triangle.

Use $j % 2 for alternating 0/1 — keep echo for digits and echo PHP_EOL; for the break, and validate row counts when reading input.

💡 Best Practices

✅ Do

  • Explain j % 2 before coding descending inner loop
  • Use echo $j % 2 for digits and echo PHP_EOL after each row
  • Validate rows ≥ 1 for interactive programs
  • Call is_numeric(trim($line)) before using rows
  • State O(n²) time when asked about complexity

❌ Don’t

  • Call echo PHP_EOL inside the inner digit loop
  • Print j directly instead of j % 2
  • Count j up when you meant this page’s descending inner loop
  • Skip the newline after each row
  • Ignore bad console input in user-facing demos
  • Skip the rows = 1 edge case

Key Takeaways

Knowledge Unlocked

Five things to remember about this binary pattern

Print the pattern the beginner-friendly way.

5
Core concepts
02

Outer loop

Grows row length each line

Code
% 03

Modulo

j % 2 picks digit

Logic
04

Newline

Ends each row

I/O
O 05

Complexity

O(n²) time

Analysis

❓ Frequently Asked Questions

Modulo 2 returns the remainder after dividing by 2. Any integer is either even (remainder 0) or odd (remainder 1).
On row 2, the inner loop prints j = 2 then j = 1. That becomes 2 % 2 = 0 then 1 % 2 = 1, so the row is 01.
echo $j % 2 stays on the same line. echo PHP_EOL ends the current line. Binary digits use echo; the row break uses echo PHP_EOL after the inner loop.
Row 3 prints j = 3, 2, 1 and j % 2 becomes 1, 0, 1 — concatenated as 101.
Program 15 counts the inner loop down (j = i to 1) producing 1, 01, 101, 0101, 10101. Program 16 counts up (j = 1 to i) producing 1, 10, 101, 1010, 10101.
Yes. Print 1 - (j % 2) instead of j % 2 to flip every digit — first row becomes 0 instead of 1.
O(n²) where n is the number of rows. Total digit prints equal n+(n-1)+…+1 = n(n+1)/2.
Use trim(fgets(STDIN)) and check is_numeric($input) before casting to int so bad input does not produce unexpected results.
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 alternating 0 and 1 using $j % 2. The inner loop counts down from $i to 1, so row length grows each line — still O(n²) total prints.

Continue to Program 16

Move on to the column-wise alternating binary pattern in the PHP number-pattern series.

Program 16 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