Topic
In this program, you'll learn how to print a diamond-shaped star pattern using Java. A diamond pattern consists of an upper and a lower triangle of stars aligned symmetrically. This program helps you understand nested loops and how to control spaces and stars for precise formatting.
Examples
Input: 5 (number of rows in the upper half)
Output:
*
***
*****
*******
*********
*******
*****
***
*
Edge Case (Input: 1)
*
Interviewer Expectations
The interviewer wants to assess your understanding of:
- Nested
forloops - Controlling spaces and characters in output
- Symmetry and loop boundaries
- Clean, readable logic with proper formatting
Approach
We divide the diamond pattern into two parts:
- Upper Half: From 1 to n rows, print increasing number of stars, centered with spaces.
- Lower Half: From n-1 to 1 rows, print decreasing stars similarly centered.
For each row:
- Print (n - row) spaces
- Print (2 * row - 1) stars
Dry Run (n = 3)
Row 1: (2 spaces, 1 star) --> " *"
Row 2: (1 space, 3 stars) --> " ***"
Row 3: (0 spaces, 5 stars) --> "*****"
Row 4: (1 space, 3 stars) --> " ***"
Row 5: (2 spaces, 1 star) --> " *"
Java Program
public class DiamondPattern {
public static void main(String[] args) {
int n = 5;
// Upper half of diamond
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n - i; j++) {
System.out.print(" ");
}
for (int j = 1; j <= 2 * i - 1; j++) {
System.out.print("*");
}
System.out.println();
}
// Lower half of diamond
for (int i = n - 1; i >= 1; i--) {
for (int j = 1; j <= n - i; j++) {
System.out.print(" ");
}
for (int j = 1; j <= 2 * i - 1; j++) {
System.out.print("*");
}
System.out.println();
}
}
}
*
***
*****
*******
*********
*******
*****
***
*
Possible Followup Questions with Answers
1. Can we print the diamond using recursion?
Yes, but recursion is not the natural fit for printing patterns. You'd have to manage spacing and star counts recursively, which adds complexity.
2. How do we center the stars correctly?
By printing n - i spaces before stars on each line, you shift stars to the right, achieving center alignment.
3. Can we print a hollow diamond?
Yes, instead of printing all stars, print stars only at boundaries:
if (j == 1 || j == 2 * i - 1) {
System.out.print("*");
} else {
System.out.print(" ");
}
4. What if we want to print the diamond with numbers or characters?
Replace System.out.print("*") with System.out.print(i) or a character like '#'.
