Number Triangle 1 to N
Problem
Read n and print a triangle. Row i contains the numbers from 1 to i, separated by one space.
Constraints
- 1 <= n <= 20
Examples
Input
3
Output
1 1 2 1 2 3
Solutions
Row i has i numbers. The inner loop starts at 1 and stops at the row number. A separator is added between numbers only.
Java 8 has no String.repeat, so we use a small helper method. In Java 11 and newer you can write " ".repeat(count).
/*
* Problem : Triangle where each row counts from 1.
* Input : One integer n (rows).
* Output : n lines of numbers.
* Approach: Inner loop counts from 1 to the row number.
* Time : O(n^2)
* Space : O(1)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int rows = new Scanner(System.in).nextInt();
// Step 1: Repeat once for each row. Row numbers go from 1 to rows.
for (int row = 1; row <= rows; row++) {
StringBuilder line = new StringBuilder();
// Step 2: Write the numbers 1, 2, ... up to the row number.
for (int number = 1; number <= row; number++) {
// Step 3: Put one space between numbers, but not before the first number.
if (number > 1) {
line.append(" ");
}
line.append(number);
}
// Step 4: Print the finished line.
System.out.println(line);
}
}
}
Hints (2)
- Use an outer loop for the rows and an inner loop for the numbers in a row.
- Write the output for n = 3 and look for the rule.