Topic
This program prints a right triangle star pattern using Java. A right triangle pattern is a simple shape that increases its number of stars with each row. It starts with one star in the first row, then two in the second, and so on.
To build this pattern, we use for loops — one to control the rows and another to control how many stars to print in each row. This is a classic beginner-level question that helps you practice nested loops.
Examples
Input: 5
Output:
*
**
***
****
*****
Input: 1
Output:
*
Input: 0
Output:
(No output as 0 rows requested)
Interviewer Expectations
The interviewer is assessing:
- Understanding of looping constructs (especially nested loops)
- Ability to convert a visual pattern into a logical structure
- Basic understanding of Java syntax, variables, and I/O
Approach
To print a right triangle star pattern:
- Take input for the number of rows (let’s call it
n). - Use an outer loop from
1tonto print each row. - Inside the outer loop, use an inner loop from
1tocurrent row numberto print stars. - After the inner loop finishes, print a new line to move to the next row.
Dry Run
Let’s dry run the input n = 3:
- Row 1 → print 1 star →
* - Row 2 → print 2 stars →
** - Row 3 → print 3 stars →
***
Java Program
public class RightTrianglePattern {
public static void main(String[] args) {
int n = 5; // Number of rows
for (int i = 1; i <= n; i++) { // Outer loop for rows
for (int j = 1; j <= i; j++) { // Inner loop for stars
System.out.print("*");
}
System.out.println(); // Move to the next line
}
}
}
*
**
***
****
*****
Possible Followup Questions with Answers
1. How would you print the triangle in reverse (upside-down)?
Start with the largest number of stars and reduce each row:
for (int i = n; i >= 1; i--) {
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
System.out.println();
}
2. How to print a right-aligned triangle?
You can add spaces before printing the stars to align the triangle to the right:
for (int i = 1; i <= n; i++) {
for (int space = 1; space <= n - i; space++) {
System.out.print(" ");
}
for (int star = 1; star <= i; star++) {
System.out.print("*");
}
System.out.println();
}
3. Can we use while or do-while loops instead?
Yes! Here's an example using while loop:
int i = 1;
while (i <= n) {
int j = 1;
while (j <= i) {
System.out.print("*");
j++;
}
System.out.println();
i++;
}
