Java ProgramsPatternsPrint Binary Triangle

Print Binary Triangle in Java

beginner·  Patterns  ·  Number Patterns

Problem

A binary triangle fills each entire row with a single repeated value — 1 for an odd-numbered row, 0 for an even-numbered row — rather than varying the value within a row.

Given a number of rows, print a triangle where every entry in row i is i modulo 2, repeated to fill that row's width.

Input
n = 5
Output
1 0 0 1 1 1 0 0 0 0 1 1 1 1 1

Java Program

Java
public class BinaryTriangle { public static void main(String[] args) { int n = 5; for (int i = 1; i <= n; i++) { int value = i % 2; // computed once per row, then repeated StringBuilder line = new StringBuilder(); for (int j = 1; j <= i; j++) { if (j > 1) line.append(" "); line.append(value); } System.out.println(line); } } }

Output

1 0 0 1 1 1 0 0 0 0 1 1 1 1 1

Core Logic

Computing a single value from the row number, then repeating it across the whole row, fills each row uniformly without needing to look at the column position at all.

How It Works
  1. 1For row i, value = i % 2 is computed once, before the inner loop even starts.
  2. 2The inner loop runs j from 1 to i, printing that same value every single time.
  3. 3Odd-numbered rows always print 1s, and even-numbered rows always print 0s, regardless of how many numbers are in that row.
  4. 4Unlike a checkerboard-style pattern, the column position j never affects what gets printed — only the row does.
For n = 5, row 3 is odd, so it prints three 1s: 1 1 1; row 4 is even, so it prints four 0s: 0 0 0 0.
💡

Key Point: Every entry in a given row is identical here — the interesting part of this pattern is which rows alternate, not what happens within a single row.

Complexity
Time Complexity: O(n²)Space Complexity: O(1)

Why: The total count of values printed is still proportional to n², even though each row only needs to compute its shared value once before repeating it.

Key Concepts

nested for loopmodulo operatorrow-uniform value

Related Programs