Challenge: Number Triangle
Completed
Read n and print a triangle of n rows. Row r contains the numbers 1 to r separated by spaces. For n = 3:
1 1 2 1 2 3
Input
One whole number n (1 ≤ n ≤ 9).
Output
n lines, no extra space at the end of a line.
Example
Input
3
Output
1 1 2 1 2 3
Editor
Java
Hints
Use one loop for the rows and one inside it for the numbers.
Print a space before every number except the first.
Solution explanation
The outer loop picks the row; the inner loop prints 1 to r. Adding the space before each number except the first avoids a space at the end.
Show solution
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for (int r = 1; r <= n; r++) {
StringBuilder line = new StringBuilder();
for (int c = 1; c <= r; c++) {
if (c > 1) {
line.append(" ");
}
line.append(c);
}
System.out.println(line);
}
}
} Output
Answer
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module