Topic: Print Mirrored Right Triangle Star Pattern
In this program, we need to print a right triangle of stars (*) that is aligned to the right side, also called a mirrored or right-justified triangle.
This is a classic problem in Java used to test understanding of nested loops, particularly how to control spaces and stars printed in the console output. You’ll learn how to use for loops effectively to generate patterns.
Examples
Input: 5
Output:
*
**
***
****
*****
Input: 3
Output:
*
**
***
Edge Case – Input: 1
*
Even with one row, the program should work correctly.
Interviewer Expectations
Interviewers use this question to test:
- Your understanding of nested
forloops - Your ability to control spacing and output format
- Logical thinking and use of loop conditions
- Basic syntax knowledge of Java
Approach
To print a mirrored triangle:
- We need
nrows (user input). - Each row contains two things:
- Some spaces first (to push stars to the right)
- Then stars
- The number of spaces in each row =
n - currentRow - The number of stars in each row =
currentRow
Dry Run (n = 4)
Row 1: 3 spaces + 1 star → " *"
Row 2: 2 spaces + 2 stars → " **"
Row 3: 1 space + 3 stars → " ***"
Row 4: 0 spaces + 4 stars → "****"
Java Program
public class MirroredTrianglePattern {
public static void main(String[] args) {
int n = 5; // Number of rows
for (int i = 1; i <= n; i++) {
// Print spaces
for (int j = 1; j <= n - i; j++) {
System.out.print(" ");
}
// Print stars
for (int k = 1; k <= i; k++) {
System.out.print("*");
}
// Move to next line
System.out.println();
}
}
}
*
**
***
****
*****
Possible Followup Questions with Answers
Q1: Can we take input from the user for number of rows?
Yes. Use Scanner class:
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of rows: ");
int n = sc.nextInt();
Q2: How do you print the same triangle but upside down?
Just reverse the outer loop and change conditions:
for (int i = n; i >= 1; i--) {
// same logic but reverse the flow
}
Q3: Can we print it with numbers instead of stars?
Yes! Replace System.out.print("*") with System.out.print(i) or any logic.
Q4: What's the time complexity of this pattern?
It’s O(n²) due to nested loops where each row has up to n iterations total.
