java

How to Print Pyramid Triangle Pattern in Java

In this tutorial, we are going to see how to print a triangle or pyramid pattern, half pyramid, and reversed pyramid, in Java programming, using the FOR loop.
 

Example 1: program to print a half pyramid
import java.util.Collections;

public class Pyramid {

    public static void main(String[] args) {

        int rows = 6;

        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("");
        }
        
    }

}

Output:

1. Half pyramid

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

Example 2: program to print a complete pyramid
import java.util.Collections;

public class Pyramid {

    public static void main(String[] args) {

        int rows = 6;

        System.out.println("\n2. Complete 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("");
        }
        
    }

}

Output:

2. Complete pyramid

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

Example 3: program to print a complete and compact pyramid
import java.util.Collections;

public class Pyramid {

 public static void main(String[] args) {

   int rows = 6;

   System.out.println("\n3. Complete pyramid - Compact\n");
   for (int i = 0; i < rows; i++) {

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

   }
        
 }

}

Output:

3. Complete pyramid - Compact

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

Example 4: program to print an reversed pyramid
import java.util.Collections;

public class Pyramid {

 public static void main(String[] args) {

   int rows = 6;

   System.out.println("\n4. Reversed pyramid\n");
   for (int i = rows; i > 0; i--) {

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

   }
        
 }

}

Output:

4. Reversed pyramid

*********
 *******
  *****
   ***
    *
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *