Sequential Decreasing-Width Number Triangle in Java

What You’ll Learn
How to print consecutive numbers in a triangle where each next row prints one fewer value.
We use System.out.format("%3d", value) to keep columns aligned.
⭐ Pattern Output
For rows = 5, the output looks like this:
1 2 3 4 5\n 6 7 8 9\n 10 11 12\n 13 14\n 15Complete Java Program
The outer loop controls rows, and the inner loop prints a decreasing count while k keeps increasing.
public class Main {
public static void main(String[] args) {
int rows = 5;
int k = 1;
for (int i = 1; i <= rows; i++) {
for (int j = rows; j >= i; j--) {
System.out.format("%3d", k++);
}
System.out.println();
}
}
}🧠 How It Works
Initialize rows and k
rows sets the triangle height. k starts at 1 and increments after each print.
Outer loop prints each row
for (int i = 1; i <= rows; i++) moves from top row to bottom row.
Inner loop decreases the width
for (int j = rows; j >= i; j--) runs fewer times as i increases, so each next row is shorter.
Format output into columns
%3d keeps numbers aligned even when they reach two digits.
Sequential triangle
The loop prints rows + (rows-1) + ... + 1 numbers, which is O(n²) overall.
Variation — User Input Version
Let the user choose the number of rows using Scanner:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of rows: ");
int rows = sc.nextInt();
int k = 1;
for (int i = 1; i <= rows; i++) {
for (int j = rows; j >= i; j--) {
System.out.format("%3d", k++);
}
System.out.println();
}
sc.close();
}
}💡 Tips for Enhancement
Try These
- Start at a different number by changing
k(e.g.,int k = 10;) - Increase the field width for larger values (e.g.,
%4d) - Build rows with
StringBuilderfor more complex formatting - Flip the triangle by changing the inner loop range
Avoid
- Hard-coding
5everywhere instead of usingrows - Forgetting
System.out.println()after each row - Using
System.out.printwithout spacing (columns can misalign for 2+ digits) - Closing
System.inif you still need console input elsewhere in the same JVM run
Key Takeaways
k stores the next number to print and increments after every output.
The inner loop count decreases as i grows, so each next row is shorter.
System.out.format("%3d", value) keeps the grid aligned.
Total prints are \(n(n+1)/2\), so runtime scales like O(n²).
❓ Frequently Asked Questions
%4d or print an extra space after each value.i from rows down to 1 and adjust the inner loop accordingly.%4d, %5d, etc.) to keep alignment as values get larger.Explore More Java Number Patterns!
Try changing the starting value and formatting width to create new sequential patterns.
You can compute total printed values in this triangle as \(1 + 2 + \dots + rows = rows(rows+1)/2\).
12 people found this page helpful
