Alternating 1 and 0 Pattern with Decreasing Width in Java

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 Java 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 Java you use one outer loop for row parity (i % 2) and one inner loop from j = i to rows to control width, then call System.out.println() 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

System.out.print the digit in the inner loop; println() 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 System.out.println().

📝 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.

Java
// rows = 5 (conceptual shape)
// 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 rowssc.nextInt();Flexible console programs
Spaced outputSystem.out.print(digit + " ")Easier reading per row

⚡ Quick Reference

GoalPattern
Walk each rowfor (i = 1; i <= rows; i++)
Pick digit by parityif (i % 2 == 0) print "0"; else print "1";
Control row widthfor (j = i; j <= rows; j++)
End the rowSystem.out.println();
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 Java 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 Scanner 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 Java programs — fixed row count, Scanner 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.

Java
public class AlternatingOneZeroPattern {
    public static void main(String[] args) {
        int rows = 5;

        for (int i = 1; i <= rows; i++) {
            for (int j = i; j <= rows; j++) {
                if (i % 2 == 0) {
                    System.out.print("0");
                } else {
                    System.out.print("1");
                }
            }
            System.out.println();
        }
    }
}

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 Scanner.nextInt() (check hasNextInt() in real apps).

Java
import java.util.Scanner;

public class AlternatingOneZeroPatternInput {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter the number of rows: ");
        int rows = sc.nextInt();

        for (int i = 1; i <= rows; i++) {
            for (int j = i; j <= rows; j++) {
                System.out.print(i % 2 == 0 ? "0" : "1");
            }
            System.out.println();
        }

        sc.close();
    }
}

How It Works

Same nested-loop core as Example 1; only the source of rows changes. Non-numeric input throws InputMismatchException with nextInt() — check hasNextInt() 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.

Java
public class AlternatingOneZeroSpaced {
    public static void main(String[] args) {
        int rows = 5;

        for (int i = 1; i <= rows; i++) {
            for (int j = i; j <= rows; j++) {
                System.out.print((i % 2 == 0 ? "0" : "1") + " ");
            }
            System.out.println();
        }
    }
}

How It Works

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

🧠 How the Algorithm Prints Rows

1

Set up

System.out is built in; use Scanner when reading input. Set rows (fixed or from input).

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 println() 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 System.out.print vs row newline without complex math.

Example: put System.out.println() 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 Scanner 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 Java 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 row/column — or rename to row/col.

  2. 2. Prefer Scanner

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

  3. 3. Keep System.out.println() Outside

    Only call System.out.println() after the inner loop finishes the row.

  4. 4. Use Ternary for Parity

    System.out.print(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 System.out.println() inside the inner loop.

Common Pitfalls

Mistakes that commonly break alternating 1/0 patterns.

  1. 1. System.out.println() Inside the Inner Loop

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

    → Use System.out.print for the digit; System.out.println() 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 System.out.println() glues every digit onto one endless line.

    → Always end the row after the inner loop.

  4. 4. Unchecked Scanner input

    Letters or empty input throw undefined rows.

    → Prefer Scanner 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 Scanner input

Unchecked Scanner leaves rows unset — call sc.hasNextInt() 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 println() only after the inner loop finishes.

💡 Best Practices

✅ Do

  • Explain parity (i % 2) and inner bounds before coding
  • Use System.out.print in the inner loop and println() after each row
  • Validate rows ≥ 1 for interactive programs
  • Check Scanner return value before using rows
  • State O(n²) time when asked about complexity

❌ Don’t

  • Call System.out.println() 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 sc.hasNextInt() before sc.nextInt() so bad input does not throw InputMismatchException.
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 Java 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