Java Program to Print a Right Triangle Star Pattern

1. Introduction

This post will guide you through writing a Java program to print a right triangle star pattern, with the number of rows based on user input. This pattern is fundamental in understanding loop constructs in Java, especially for beginners. By allowing the user to determine the size of the triangle, this program also introduces basic input handling in Java.

2. Program Steps

1. Import the Scanner class for taking user input.

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

3. Use a for loop to iterate through each row and print the appropriate number of stars (*) for each row, based on the current iteration number.

4. Compile and run the program, input the desired number of rows, and observe the right triangle star pattern printed on the console.

3. Code Program

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

public class RightTriangleStarPattern {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in); // Create 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 = 1; i <= rows; i++) { // Loop for each row
            for(int j = 1; j <= i; j++) { // Loop to print stars equal to the row number
                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 begins by importing the Scanner class to enable user input through the console.

2. It then prompts the user to enter the number of rows for the triangle. This input determines how tall the right triangle will be.

3. A for loop (for(int i = 1; i <= rows; i++)) iterates from 1 to the user-specified number of rows. For each iteration, a nested loop prints a number of stars (*) equal to the current row number, creating the right triangle pattern.

4. After printing the stars for a row, the program outputs a newline character (System.out.println()), moving to the next line to continue the pattern.

5. The Scanner object is closed with scanner.close() at the end of the program to prevent resource leaks, following best practices for handling user input in Java.

Comments