Mirror Image Triangular Number Pattern in Java

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:

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

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:

Enter the number of rows: 6
     0
    101
   21012
  3210123
 432101234
54321012345