Diamond Number-Star Pattern (Sandwich Inverted)
Understanding the Problem
The goal is to print a diamond-shaped pattern where numbers are printed in decreasing order in the upper half, followed by a repeated middle row, and then increasing order in the lower half. Each number is followed by a star except for the last number in each row.
Pattern Explanation
The pattern consists of three parts: the upper half, the repeated middle row, and the lower half.
6*6*6*6 5*5*5 4*4 3 3 4*4 5*5*5 6*6*6*6
Observations:
- The pattern consists of 7 rows.
- Numbers decrement from 6 to 3 in the upper half.
- The middle row (3) is repeated once.
- Each number is followed by a '*', except for the last number in each row.
- The lower half mirrors the upper half, incrementing from 4 to 6.
Algorithm
The pattern follows these steps:
- Initialize a variable to determine the maximum number (N).
- Loop through rows from N down to 3 to print the upper half of the diamond.
- For each row, loop through columns (up to the current row number) and print the current row number.
- Print the number followed by '*' except for the last number in the row.
- After completing the upper half, print the middle row (3) again.
- Loop through rows from 4 to N to print the lower half of the diamond.
- Repeat steps 3 and 4 for the lower half.
- Move to the next line after printing each row.
Method 1: Using Nested Loops
This method uses two loops to print the pattern.
public class DiamondNumberStarPatternSandwichInverted { public static void main(String[] args) { int n = 6; // Maximum number for the diamond pattern // Loop to print the upper half of the diamond for (int i = n; i >= 3; i--) { // Loop for each row for (int j = 1; j <= (n - i + 1); j++) { // Loop for each column in the current row System.out.print(i); // Print the current row number if (j < (n - i + 1)) System.out.print("*"); // Print '*' if not the last number in the row } System.out.println(); // Move to the next line after each row } // Print the middle row again System.out.println("3"); // Print the middle number // Loop to print the lower half of the diamond for (int i = 4; i <= n; i++) { // Loop for each row for (int j = 1; j <= (i - 3); j++) { // Loop for each column in the current row System.out.print(i); // Print the current row number if (j < (i - 3)) System.out.print("*"); // Print '*' if not the last number in the row } System.out.println(); // Move to the next line after each row } } }
Output:
6*6*6*6 5*5*5 4*4 3 3 4*4 5*5*5 6*6*6*6