Java Practice Program: inverted pyramid

Write a Java program that prints an inverted pyramid of stars.

This Java program generates an inverted pyramid of stars. It uses nested loops, where the number of stars decreases row by row, creating an inverted triangular shape.

class Main {
    public static void main(String[] args) {
        final int ROW_COUNT = 5;  // Number of rows in the pyramid

        // Outer loop for each row
        for (int row = ROW_COUNT; row >= 1; row--) {
            // Loop for spaces before stars
            for (int space = ROW_COUNT; space > row; space--) {
                System.out.print(" ");
            }

            // Loop to print stars
            for (int star = 1; star <= (2 * row - 1); star++) {
                System.out.print("*");
            }

            // Move to the next line after each row
            System.out.println();
        }
    }
}

Output:

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

final int ROW_COUNT = 5;

Specifies the total number of rows in the pyramid. Declared as final to indicate it doesn’t change during execution.
Outer Loop (for (int row = ROW_COUNT; row >= 1; row–))

Controls the number of rows.
Starts from the maximum number of rows (ROW_COUNT) and decreases to 1.
First Inner Loop (Spaces) (for (int space = ROW_COUNT; space > row; space–))

Adds spaces before the stars to align the pyramid correctly.
As the number of rows (row) decreases, the number of spaces increases.
Second Inner Loop (Stars) (for (int star = 1; star <= (2 * row – 1); star++))

Prints the stars for each row.
For each row, the number of stars is given by the formula 2 * row – 1.
As row decreases, the number of stars decreases.
System.out.println();

Moves to the next line after printing stars for a row.

Key Points
Spaces Alignment:
The spaces increase as the rows decrease to maintain the inverted pyramid shape.
Number of Stars:

The number of stars in row n is 2 * n – 1.

Customizations:
To change the size of the pyramid, modify ROW_COUNT.
Replace “*” with another character if desired.

Logic for Alignment:
The first inner loop ensures proper alignment by printing spaces.
The second inner loop adjusts the number of stars according to the row index.

Leave a Reply