Java Program to Print an Inverted Right Triangle Star Pattern

1. Introduction

In this tutorial, we'll learn how to write a Java program that prints an inverted right triangle star pattern, with the height determined by the user's input. This pattern is a great exercise for understanding not only loop constructs but also how to manipulate these loops to achieve a desired output pattern. Taking user input to determine the size of the triangle introduces an interactive element to the program, making it more dynamic and flexible.

2. Program Steps

1. Import the Scanner class to enable reading input from the user.

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

3. Use a for loop to iterate through the rows in reverse order, decrementing from the user-specified number of rows to 1.

4. Inside the loop, use a nested for loop to print the appropriate number of stars (*) for each row.

5. Compile and execute the program, then input the desired number of rows to see the inverted right triangle pattern printed on the console.

3. Code Program

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

public class InvertedRightTrianglePattern {
    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 user input
        int rows = scanner.nextInt(); // Read number of rows from user

        for(int i = rows; i >= 1; i--) { // Loop for each row in reverse order
            for(int j = 1; j <= i; j++) { // Loop to print stars
                System.out.print("*"); // Print star
            }
            System.out.println(); // New line after each row
        }
        scanner.close(); // Close the scanner
    }
}

Output:

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

Explanation:

1. The program starts by importing the Scanner class, necessary for obtaining user input through the console.

2. It prompts the user to enter the desired number of rows for the inverted right triangle. This input decides the starting point for the number of stars in the first row.

3. A descending for loop (for(int i = rows; i >= 1; i--)) is used to iterate from the number of rows entered by the user down to 1, reducing the number of iterations and thus the number of stars printed in each subsequent row.

4. Within this loop, a nested for loop prints the stars for each row. The number of stars starts from the user-defined number and decreases by one with each descending row, forming an inverted right triangle.

5. The Scanner object is closed with scanner.close() to prevent resource leaks, following good practice for input handling in Java.

Comments