Sequential Number Triangle (i + j - 1) in Java

What You’ll Learn
How to print a sequential number triangle in Java:
1, then 2 3, then 3 4 5, and so on.
You’ll generate each number with the simple formula i + j - 1, where i is the row and j is the column.
⭐ Pattern Output
For rows = 5, the pattern looks like this:
1
2 3
3 4 5
4 5 6 7
5 6 7 8 9Complete Java Program
The outer loop controls the row count. The inner loop prints i values, and each value is computed as i + j - 1.
public class Main {
public static void main(String[] args) {
int rows = 5;
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= i; j++) {
System.out.print((i + j - 1) + " ");
}
System.out.println();
}
}
}🧠 How It Works
Set the row count
int rows = 5; controls the triangle height.
Outer loop controls rows
for (int i = 1; i <= rows; i++) increases the row length from 1 up to rows.
Inner loop prints i values
for (int j = 1; j <= i; j++) prints one value per column on the current row.
Compute the value as i + j - 1
On each row, the first value is i (because j=1). Then it increases by 1 as j moves across the row.
Sequential i+j-1 triangle
Total numbers printed are 1+2+…+n = n(n+1)/2, so time complexity is O(n²).
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();
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= i; j++) {
System.out.print((i + j - 1) + " ");
}
System.out.println();
}
sc.close();
}
}💡 Tips for Enhancement
Try These
- Avoid trailing spaces by printing a space only when
j < i - Right-align the triangle by printing leading spaces before each row
- Change the expression (for example
i + jori * j) to create new patterns - Use
StringBuilderif you want custom separators (comma, dash, etc.) - Try printing odd numbers only by using
2 * (i + j - 1) - 1
Avoid
- Hard-coding 5 instead of using
rows - Mixing up row and column indices (keep
ifor rows,jfor columns) - Forgetting the newline after each row
- Closing
System.intoo early if you need more input later
Key Takeaways
Row i prints exactly i values.
The first value on each row is i (because i + 1 - 1 = i).
The formula i + j - 1 increases by 1 across the row.
Total printed values are n(n+1)/2, so runtime is O(n²).
❓ Frequently Asked Questions
j=1, so the formula becomes i + 1 - 1, which equals i.j < i. That keeps spaces between values but not at the end of the row.(start - 1) + i + j - 1. For example, start at 10 with 9 + i + j - 1.Explore More Java Number Patterns!
Try swapping the value formula to generate brand-new sequences with the same nested-loop structure.
The expression i + j - 1 is a simple example of a diagonal pattern: numbers along each diagonal are the same, because they share the same i + j sum.
12 people found this page helpful
