Topic
In this program, we will learn how to print an inverted pyramid star pattern using Java. An inverted pyramid is a pattern where the top row contains the most stars, and each subsequent row contains two fewer stars, centered properly using spaces.
This problem helps beginners understand nested loops — one loop for rows and another for handling spaces and stars on each row.
Examples
Example 1 (n = 5):
*********
*******
*****
***
*
Example 2 (n = 3):
*****
***
*
Example 3 (Edge Case: n = 1):
*
Interviewer Expectations
The interviewer wants to assess your understanding of:
- Nested
forloops - How to manage spaces and stars for symmetrical patterns
- Basic arithmetic and loop conditions
- Clean code structure and proper indentation
Approach
Let’s break it down:
- We take a number
nas the input which represents the number of rows in the pyramid. - We use an outer loop to control the number of rows.
- For each row:
- Print spaces on the left to center the stars
- Then print the stars: number of stars is
2 * i - 1whereiis the current row number fromnto 1
Dry Run (n = 3)
Row 1: spaces = 0, stars = 2*3-1 = 5 => *****
Row 2: spaces = 1, stars = 2*2-1 = 3 => ***
Row 3: spaces = 2, stars = 2*1-1 = 1 => *
Java Program
without newline for each star.",
"After the stars, we move to the next line using System.out.println().",
"Repeat the above steps for each decreasing row until i = 1.",
"At the end, we have a complete inverted pyramid pattern printed.",
"The main method ends here."
]'>public class InvertedPyramidPattern {
public static void main(String[] args) {
int n = 5;
for (int i = n; i >= 1; i--) {
for (int space = 0; space < n - i; space++) {
System.out.print(" ");
}
for (int star = 0; star < 2 * i - 1; star++) {
System.out.print("*");
}
System.out.println();
}
}
}
*********
*******
*****
***
*
Possible Followup Questions with Answers
Q1: How would you print a normal (non-inverted) pyramid star pattern?
You would reverse the loop to go from 1 to n and adjust the space and star logic accordingly:
for (int i = 1; i <= n; i++) {
for (int space = 0; space < n - i; space++) {
System.out.print(" ");
}
for (int star = 0; star < 2 * i - 1; star++) {
System.out.print("*");
}
System.out.println();
}
Q2: Can you make the stars print with a space in between, like "* * * * *"?
Yes, just print "* " instead of "*" inside the inner loop for stars.
Q3: What if we want the pattern to be left-aligned instead of centered?
Skip printing spaces before stars and just reduce the number of stars per row.
Q4: How do you make the pattern dynamic based on user input?
Use Scanner to read value of n from user:
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
Q5: What are common mistakes beginners make in such pattern problems?
- Incorrect loop boundaries
- Using
System.out.println()instead ofSystem.out.print()inside inner loops - Getting space and star counts wrong
