Java – How to print a Pyramid

A Java example to print half and full pyramid, for fun.

CreatePyramid.java

package com.mkyong;

import java.util.Collections;

public class CreatePyramid {

    public static void main(String[] args) {

        int rows = 5;

        System.out.println("\n1. Half Pyramid\n");
        for (int i = 0; i < rows; i++) {

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

            System.out.println("");
        }

        System.out.println("\n2. Full Pyramid\n");
        for (int i = 0; i < rows; i++) {

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

            for (int k = 0; k <= i; k++) {
                System.out.print("* ");
            }

            System.out.println("");
        }

        //java 8 , one line
        System.out.println("\n3. Full Pyramid (Compact)\n");
        for (int i = 0; i < rows; i++) {

            System.out.println(String.join("", Collections.nCopies(5 - i - 1, " "))
                    + String.join("", Collections.nCopies(2 * i + 1, "*")));

        }

        // java 8
        System.out.println("\n4. Inverted Pyramid\n");
        for (int i = rows; i > 0; i--) {

            System.out.println(String.join("", Collections.nCopies(5 - i, " "))
                    + String.join("", Collections.nCopies(2 * i - 1, "*")));

        }

    }

}

Output


1. Half Pyramid

*
**
***
****
*****

2. Full Pyramid

     * 
    * * 
   * * * 
  * * * * 
 * * * * * 

3. Full Pyramid (Compact)

    *
   ***
  *****
 *******
*********

4. Inverted Pyramid

*********
 *******
  *****
   ***
    *
	

References

  1. Collections.nCopies JavaDoc
  2. Python – Print a pyramid

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar
7 Comment threads
0 Thread replies
1 Followers
 
Most reacted comment
Hottest comment thread
7 Comment authors
pkumarMonirJoeHxNavneettutoref Recent comment authors
newest oldest most voted
Ran Cohen
Guest
Ran Cohen

In Java 8, a *REAL* one line of Half Pyramid:
Arrays.stream(new int[]{1, 2, 3, 4, 5}).forEach(i -> System.out.println(String.format(“%0” + i + “d”, 0).replace(“0”, “*”)));
:)

tutoref
Guest
tutoref

I used to do this for fun …

Pavan Solapure
Guest
Pavan Solapure

You made me remember my academic days :). We have come a long way since then. Very sophisticated and neat!!!

pkumar
Guest
pkumar

same like print pyramid in c or c++
only some syntax difference.

Monir
Guest
Monir

Well! you really back my old day’s memory. Can we try a little different solution, like printing the above pyramid without using any loop? Also not like a solution to use a series of a print statement.

JoeHx
Guest
JoeHx

It’s like “Hello, World,” but challenging. I like it!

Navneet
Guest
Navneet

Explained Very well.

Thanks.