Print Repeated Number Pattern in Java
Problem
Instead of counting up through a row like a plain number triangle, this pattern holds one fixed value per row — the row number itself — and repeats only that.
Given a number of rows, print a triangle where row i consists of the number i repeated i times.
Java Program
public class RepeatedNumberPattern {
public static void main(String[] args) {
int n = 5;
for (int i = 1; i <= n; i++) {
StringBuilder row = new StringBuilder();
for (int j = 0; j < i; j++) {
if (j > 0) row.append(" ");
row.append(i); // same value repeated across the whole row
}
System.out.println(row);
}
}
}Output
Core Logic
Printing the row index itself, i times per row, builds a growing triangle without ever incrementing the value being printed.
- 1The outer loop runs
ifrom1ton, one row per value ofi. - 2The inner loop runs exactly
itimes, printingiitself on every pass — not a counter that changes. - 3Each row therefore shows a single number repeated, rather than a run of consecutive numbers.
- 4Row width still grows by one each time, the same shape as any other increasing triangle.
4 across all four positions: 4 4 4 4.Key Point: This differs from Number Triangle, which counts 1 through i across a row — here every position in a row holds the exact same value, the row number itself.
Why: The total values printed across every row grows proportionally to n², with only the two loop counters kept in memory.
Key Concepts
Approach 2: Java 8
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class RepeatedNumberPatternStream {
public static void main(String[] args) {
int n = 5;
IntStream.rangeClosed(1, n)
.mapToObj(i -> IntStream.range(0, i)
.mapToObj(j -> String.valueOf(i)) // ignores j, always yields the row's own value
.collect(Collectors.joining(" ")))
.forEach(System.out::println);
}
}
Output
Core Logic
Mapping every position in a row to the same fixed row value, rather than to the position itself, is what tells the stream to repeat instead of count.
- 1
IntStream.rangeClosed(1, n)generates one stream element per row. - 2For each row
i, an innerIntStream.range(0, i)generatesipositions. - 3
.mapToObj(j -> String.valueOf(i))ignores the positionjentirely and always yieldsi. - 4
Collectors.joining(" ")joins that row's repeated values beforeforEachprints it.
"4", giving "4 4 4 4".Key Point: The inner stream's position variable j is generated but never used in the mapping — it only controls how many times the row value repeats.
Why: The nested streams still produce one value per grid position across all rows, proportional to n², without collecting the full triangle.