Java Program to Print an Inverted Pyramid

1. Introduction

This blog post focuses on creating a Java program that prints an inverted pyramid pattern, with the number of rows determined by user input. Inverted pyramids are a fascinating way to demonstrate control structures, user input handling, and loop constructs in Java. This program is slightly more advanced than a basic pyramid printer because it involves dynamically adjusting the program's behavior based on user input, offering a great way to engage with fundamental programming concepts.

2. Program Steps

1. Import the Scanner class for taking user input.

2. Prompt the user to enter the number of rows for the inverted pyramid.

3. Use a for loop to iterate over the rows in reverse order to create the inverted pyramid.

4. Inside the loop, use nested loops: one for printing spaces and another for printing asterisks (*), to form the inverted shape.

5. Compile and execute the program, and enter the desired number of rows to see the inverted pyramid pattern on the console.

3. Code Program

import java.util.Scanner; // Import Scanner class

public class InvertedPyramidPattern {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in); // Create a Scanner object
        System.out.print("Enter the number of rows: "); // Prompt for rows
        int rows = scanner.nextInt(); // Read user input for rows

        for(int i = rows; i >= 1; i--) { // Loop for each row in reverse
            for(int j = rows; j > i; j--) { // Loop for spaces
                System.out.print(" "); // Printing space
            }
            for(int k = 1; k <= (2 * i - 1); k++) { // Loop for asterisks
                System.out.print("*"); // Printing asterisk
            }
            System.out.println(); // New line after each row
        }
        scanner.close(); // Close the scanner
    }
}

Output:

Enter the number of rows: 5
*********
 *******
  *****
   ***
    *

Explanation:

1. The program begins by importing the Scanner class, which is used to take user input from the console.

2. It then prompts the user to enter the number of rows for the inverted pyramid.

3. A for loop iterates in reverse order from the number of rows to 1. This reverse iteration is crucial for creating the inverted pyramid effect.

4. Inside the loop, two nested loops are used: the first prints the spaces required to align the pyramid correctly on the right side, and the second prints the asterisks (*). As the loop progresses, the number of asterisks decreases, forming the inverted pyramid shape.

5. After printing the required spaces and asterisks for a row, a newline character is inserted to move to the next line, ensuring the pyramid shape is maintained.

6. Finally, the Scanner object is closed to prevent resource leaks, a good practice when dealing with I/O operations in Java.

Comments