Write a Java program that prints a right-angled triangle pattern.
This Java program prints a right-angled triangle pattern using asterisks (*
). The number of rows in the triangle is specified by the variable row
, and the number of stars in each row increases as you move down.
class Main {
public static void main(String[] args) {
int row=5;
for(int i=1;i<=row;i++){
for(int j=1;j<=i;j++){
System.out.print("* ");
}
System.out.println();
}
}
}
Output:
*
* *
* * *
* * * *
* * * * *
Code Breakdown
int row = 5;
The variable row is used to set the number of rows in the pattern. Here, it’s set to 5, meaning the pattern will have 5 rows.
Outer Loop (for (int i = 1; i <= row; i++))
The outer loop controls the rows. It runs 5 times (from i = 1 to i = 5), one for each row of the pattern.
The variable i represents the current row number.
Inner Loop (for (int j = 1; j <= i; j++))
The inner loop controls the number of stars printed in each row. The number of stars increases as i increases.
For row i = 1, it prints 1 star; for row i = 2, it prints 2 stars; and so on.
System.out.print(“* “);
Prints a star (*) followed by a space. The print method is used instead of println to prevent the cursor from moving to the next line after printing each star.
System.out.println();
After the inner loop finishes for a row, this statement prints a newline, moving the cursor to the next row.
Key Points
- Pattern Formation: The number of stars in each row is equal to the row number. Row 1 has 1 star, row 2 has 2 stars, and so on.
- Flexible Row Count: You can change the value of row to print a larger or smaller pattern.
- Nested Loops: The outer loop manages the rows, and the inner loop prints the stars for each row. The combination of the two loops creates the desired pattern.