Java Program to Create Pyramid Of Numbers

In this post, we will write a Java program to create a pyramid of numbers with the below patterns.
1. Triangle Pyramid 
2. Reverse Triangle Pyramid 
3. Pyramid 
4. Reverse Pyramid 
1
12
123
1234
12345
123456
1234567
12345678
123456789
12345678910

12345678910
123456789
12345678
1234567
123456
12345
1234
123
12
1

         
        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 8 9 

 1 2 3 4 5 6 7 8 9 10 
  1 2 3 4 5 6 7 8 9 
   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 
           

Java Program to Create Pyramid Of Numbers

package net.javaguides.corejava.arrays.programs;

public class PyramidsExamples {

    public static void main(final String[] args) {

        trianglePyramid(10);

        System.out.println();

        reverserTrianglePyramid(10);

        System.out.println();

        pyramid(9);

        System.out.println();

        reversePyramid(10);
    }

    public static void trianglePyramid(final int n) {
        for (int i = 0; i <= n; i++) {
            for (int j = 1; j <= i; j++) {
                System.out.print(j);
            }
            System.out.println();
        }
    }

    public static void reverserTrianglePyramid(final int n) {
        for (int i = n; i > 0; i--) {
            for (int j = 1; j <= i; j++) {
                System.out.print(j);
            }
            System.out.print("\n");
        }
    }

    public static void pyramid(final int n) {
        for (int i = 0; i <= n; i++) {
            for (int j = 0; j < n - i; j++) {
                System.out.print(" ");
            }
            for (int k = 1; k <= i; k++) {
                System.out.print(k + " ");
            }
            System.out.println();
        }
    }

    public static void reversePyramid(final int n) {
        for (int i = n; i >= 0; i--) {

            for (int j = 0; j <= n - i; j++) {
                System.out.print(" ");
            }

            for (int k = 1; k <= i; k++) {
                System.out.print(k + " ");
            }
            System.out.println();
        }
    }
}
Output:

1
12
123
1234
12345
123456
1234567
12345678
123456789
12345678910

12345678910
123456789
12345678
1234567
123456
12345
1234
123
12
1

         
        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 8 9 

 1 2 3 4 5 6 7 8 9 10 
  1 2 3 4 5 6 7 8 9 
   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 
           

Comments