Print Binary Triangle in Java
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.
Java Program
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
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.
- 1For row
i,value = i % 2is computed once, before the inner loop even starts. - 2The inner loop runs
jfrom 1 toi, printing that samevalueevery single time. - 3Odd-numbered rows always print
1s, and even-numbered rows always print0s, regardless of how many numbers are in that row. - 4Unlike a checkerboard-style pattern, the column position
jnever affects what gets printed — only the row does.
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.
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.