Java Code Example: Triangle Pattern

This code prints a triangle pattern of numbers, where each row contains consecutive numbers from 1 to the row number. The first half of the pattern consists of rows with increasing numbers, while the second half consists of rows with decreasing numbers.

Code Example

public class TrianglePattern {
    public static void main(String[] args) {
        int rows = 8;

        // Print the first half of the pattern
        for (int i = 1; i <= rows; i++) {
            for (int j = 1; j <= i; j++) {
                System.out.print(j + " ");
            }
            System.out.println();
        }

        // Print the second half of the pattern
        for (int i = rows - 1; i >= 1; i--) {
            for (int j = 1; j <= i; j++) {
                System.out.print(j + " ");
            }
            System.out.println();
        }
    }
}

Output

1 
1 2 
1 2 3 
1 2 3 4 
1 2 3 4 5 
1 2 3 4 5 6 
1 2 3 4 5 6 7 
1 2 3 4 5 6 7 8 
1 2 3 4 5 6 7 
1 2 3 4 5 6 
1 2 3 4 5 
1 2 3 4 
1 2 3 
1 2 
1 

Code Explanation

The rows variable sets the number of rows in the pattern, and can be changed to a different value.
The first for loop prints the first half of the pattern, with i representing the current row number and j representing the current column number.

The second for loop prints the second half of the pattern, using a similar structure but with the rows printed in reverse order.
The println() method is used to move to a new line after each row is printed.