The Upper Star Triangle Pattern is one of the most common pattern-printing programs in Java. It helps beginners understand nested loops, spacing, and row-column relationships. In this pattern, the number of stars increases by one in each row, forming a right-angled triangle.
- Leading spaces decrease with each row.
- Helps improve understanding of loop control and pattern generation.
Illustration:
Input: Rows = 5
Output: *
**
***
****
*****
Approach
- Initialize the number of rows.
- Use an outer loop to iterate through each row.
- Print the required leading spaces using the first inner loop.
- Print the stars using the second inner loop.
- Move to the next line after completing each row.
public class GFG {
public static void main(String[] args) {
int rows = 5;
// Print rows
for (int i = 1; i <= rows; i++) {
// Print leading spaces
for (int j = 1; j <= rows - i; j++) {
System.out.print(" ");
}
// Print stars
for (int k = 1; k <= i; k++) {
System.out.print("*");
}
System.out.println();
}
}
}
Output
* ** *** **** *****
Explanation: The outer loop controls the number of rows. The first inner loop prints the leading spaces, while the second inner loop prints stars equal to the current row number, forming an upper star triangle.