How to print a triangle of asterisks in Java?

To create a triangle of asterisks, you can use nested loops. Here is an example code written in Java:

public class TriangleStar {
    public static void main(String[] args) {
        int rows = 5;
        
        for (int i = 1; i <= rows; i++) {
            for (int j = 1; j <= i; j++) {
                System.out.print("* ");
            }
            System.out.println();
        }
    }
}

In the above code, we use two for loops to control rows and columns. The outer loop controls the number of rows, iterating from 1 to the specified number of rows (which is 5 here). The inner loop controls the number of columns in each row, iterating from 1 to the current row number. Within the inner loop, we use System.out.print(“* “) to print asterisks and System.out.println() to output a line break after each row ends.

Running the above code will produce the following triangle of asterisks.

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

You can adjust the value of rows as needed to output triangles with different numbers of lines of asterisks.

广告
Closing in 10 seconds
bannerAds