Java Program to Print an Inverted Pyramid

Introduction

Printing patterns like pyramids and triangles is a common programming exercise to help understand how nested loops work. In this guide, we will create a Java program to print an inverted pyramid pattern using stars (*).

Problem Statement

Create a Java program that:

  • Accepts the size of the pyramid.
  • Prints an inverted pyramid using stars (*).

Example:

  • Input: size = 5
  • Output:
    *********
     *******
      *****
       ***
        *
    

Solution Steps

  1. Input the Size of the Pyramid: The size defines how many rows the inverted pyramid will have.
  2. Use Nested Loops: Use loops to print the stars and spaces required for the pyramid.
  3. Display the Inverted Pyramid: Print stars in decreasing order with spaces on the left for proper alignment.

Java Program

// Java Program to Print an Inverted Pyramid
// Author: [Your Name]

import java.util.Scanner;

public class InvertedPyramid {
    public static void main(String[] args) {
        // Step 1: Accept the size of the pyramid
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter the size of the inverted pyramid: ");
        int size = sc.nextInt();

        // Step 2: Outer loop for the rows
        for (int i = size; i >= 1; i--) {
            // Step 3: Print spaces for alignment
            for (int j = size; j > i; j--) {
                System.out.print(" ");
            }

            // Step 4: Print stars in each row
            for (int k = 1; k <= (2 * i - 1); k++) {
                System.out.print("*");
            }

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

        // Closing the scanner object
        sc.close();
    }
}

Explanation

Step 1: Input Size

  • The program begins by taking input from the user for the size of the pyramid. This size determines how many rows will be printed.

Step 2: Outer Loop for Rows

  • The outer loop controls how many rows are printed, starting from size and decreasing down to 1.

Step 3: Print Spaces for Alignment

  • For each row, the inner loop prints spaces to ensure proper alignment of stars. The number of spaces increases as the row number decreases.

Step 4: Print Stars

  • The number of stars printed decreases for each row. The pattern follows the formula 2 * i - 1, where i is the current row number. This ensures that the stars form an inverted pyramid.

Output Example

For size = 5, the output is:

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

For size = 7, the output is:

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

Conclusion

This Java program prints an inverted pyramid of stars by using nested loops. The program handles alignment with spaces and decreases the number of stars for each row, creating an inverted pyramid. This is a great way to practice pattern generation using loops in Java.

Comments