Java Program to Print a Hollow Pyramid

1. Introduction

Today, we're exploring how to create a Java program that prints a hollow pyramid pattern. This program adds a twist to the regular pyramid by leaving the inside of the pyramid empty, which introduces the concept of conditionally printing characters. It's a fantastic way to learn about nested loops and conditional statements in Java, providing a deeper understanding of how to manipulate output to create complex patterns.

2. Program Steps

1. Initialize the necessary variables for the number of rows in the pyramid.

2. Use a for loop to iterate over the rows of the pyramid.

3. Inside the loop, use nested loops and conditional statements to print spaces and asterisks (*) such that only the border of the pyramid is printed, leaving the inside hollow.

4. Compile and run the program to see the hollow pyramid pattern printed on the console.

3. Code Program

public class HollowPyramidPattern {
    public static void main(String[] args) {
        int rows = 5; // Number of pyramid rows

        for(int i = 1; i <= rows; i++) { // Loop for each row
            for(int j = i; j < rows; j++) { // Loop for spaces before asterisks
                System.out.print(" "); // Printing space
            for(int k = 1; k <= (2 * i - 1); k++) { // Loop for asterisks and hollow
                if(k == 1 || k == (2 * i - 1) || i == rows) {
                    System.out.print("*"); // Print asterisk at borders and last row
                } else {
                    System.out.print(" "); // Print space inside the pyramid
            System.out.println(); // New line after each row


   * *
  *   *
 *     *


1. The program initializes with a set number of rows for the pyramid (rows = 5).

2. It uses a for loop to iterate through each row, starting from 1 to maintain the correct pyramid structure.

3. For each row, a nested for loop first prints the spaces needed to align the pyramid's left side correctly.

4. Another nested for loop is responsible for printing the asterisks. This loop includes a conditional statement to ensure that asterisks are printed only at the borders of the pyramid and the base (last row), creating the hollow effect inside (if(k == 1 || k == (2 * i - 1) || i == rows)).

5. After printing the required spaces and asterisks for a row, a newline character is used to move to the next line, ensuring that the pyramid shape is correctly formed.

6. This process repeats until the hollow pyramid pattern is completed for the specified number of rows, resulting in a visually appealing pattern that demonstrates the use of basic control structures in Java.