Java Program to Print a Left Triangle Star Pattern

1. Introduction

In this guide, we'll explore how to create a Java program that prints a left triangle star pattern, where the height of the triangle is determined by user input. This pattern is interesting because it aligns the stars to the left, making it a good exercise for understanding loops and input handling in Java. By implementing user input, the program becomes interactive, allowing the user to control the size of the triangle.

2. Program Steps

1. Import the Scanner class to read input from the console.

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

3. Use a for loop to iterate over each row. Within this loop, implement two nested loops: the first to print spaces and the second to print stars (*), aligning the triangle to the left.

4. Compile and execute the program. Enter the number of rows when prompted to generate the left triangle star pattern.

3. Code Program

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

public class LeftTriangleStarPattern {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in); // Create Scanner object for input
        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 = 0; i < rows; i++) { // Loop for each row
            for(int j = 2 * (rows - i); j >= 0; j--) { // Loop for spaces
                System.out.print(" "); // Print space
            }
            for(int k = 0; k <= i; k++) { // Loop for stars
                System.out.print("* "); // Print star and space
            }
            System.out.println(); // New line after each row
        }
        scanner.close(); // Close scanner to prevent resource leak
    }
}

Output:

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

Explanation:

1. The program begins by importing the Scanner class, which is necessary for capturing user input from the console.

2. It then prompts the user to input the number of rows desired for the left triangle pattern. This input determines the overall height of the triangle.

3. A for loop iterates over the rows, with each iteration corresponding to a row of the triangle. Within this loop, there are two nested loops: the first prints spaces to align the triangle to the left, and the second prints the stars that form the triangle. The number of spaces decreases with each row, while the number of stars increases, creating the left-aligned triangle shape.

4. After printing the required spaces and stars for a row, a newline character is used to move to the next line, continuing the pattern until the final row is reached.

5. Lastly, the Scanner object is closed with scanner.close() to prevent resource leaks, adhering to best practices for handling user input in Java.

Comments