In this tutorial, we will write a program to print a triangle pattern in java where the pattern is repeated by dividing each row in two half just like a mirror. Before that, you may go through the following topic in java.
Example:
1 2 3 4 5 6 7 | Input: 5 Output: 0 101 21012 3210123 432101234 |
The program takes the user input for the number of rows and displays the result using the for loop in java. The program is a mirror triangle number pattern in java or you can say full pyramid of numbers with mirror image numbers.
Program for triangular pattern
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | import java.util.Scanner; public class Main { public static void main(String[] args) { int rows, num1 = 1, num2 = 1; Scanner sc = new Scanner(System.in); System.out.print("Enter the number of rows: "); rows = sc.nextInt(); for (int i = 0; i < rows; i++) { for (int j = rows - 1; j > i; j--) { System.out.print(" "); } for (int k = 1; k <= num1; k++) { System.out.print(Math.abs(k - num2)); } num1 += 2; num2++; System.out.println(); } } } |
Output:
1 2 3 4 5 6 7 | Enter the number of rows: 6 0 101 21012 3210123 432101234 54321012345 |