Creating Stunning Diamond Patterns in Java with Nested Loops
1 min readNov 6, 2023
public void printPattern(int n) {
int i, j;
// outer loop to handle number of rows
for (i = 1; i <= n; i++) {
// inner loop to print the spaces
for (j = 1; j <= 2 * (n - i); j++) {
System.out.print(" ");
}
// inner loop to print the first part
for (j = i; j >= 1; j--) {
System.out.print(j + " ");
}
// inner loop to print the second part
for (j = 2; j <= i; j++) {
System.out.print(j + " ");
}
// printing new line for each row
System.out.println();
}
}
Output
1
2 1 2
3 2 1 2 3
4 3 2 1 2 3 4
5 4 3 2 1 2 3 4 5
6 5 4 3 2 1 2 3 4 5 6
Here’s how it all comes together:
- The outer loop takes charge of managing the number of rows.
- The first inner loop works its magic by printing spaces.
- The second inner loop creates the first part of the pattern.
- The third inner loop brings in the second part.
Thanks to these cleverly managed number patterns, you’ll witness a stunning diamond shape emerge.
Key Takeaways:
- The spacing is meticulously crafted to align the center of the diamond.
- Symmetry is achieved through creative inner loop ranges.
- The use of multiple inner loops constructs different segments of the diamond.