Basic Diamond Number-Star Pattern

Understanding the Problem

The goal is to print a diamond-shaped pattern where numbers are printed in increasing order in the upper half and decreasing order in the lower half, with each number followed by a star except for the last number in each row.

Pattern Explanation

The pattern consists of two halves: the upper half where numbers increment and the lower half where numbers decrement.

1
2*2
3*3*3
4*4*4*4
3*3*3
2*2
1
            

Observations:

  • The pattern consists of 7 rows.
  • Numbers increment from 1 to 4 in the upper half.
  • Each number is followed by a '*', except the last number in each row.
  • The lower half mirrors the upper half, decrementing from 3 to 1.

Algorithm

The pattern follows these steps:

  1. Initialize a variable to determine the maximum number (N).
  2. Loop through rows from 1 to N to print the upper half of the diamond.
  3. For each row, loop through columns (up to the current row number) and print the current row number.
  4. Print the number followed by '*' except for the last number in the row.
  5. After completing the upper half, loop through rows from N-1 down to 1 to print the lower half of the diamond.
  6. Repeat steps 3 and 4 for the lower half.
  7. 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 DiamondNumberStarPattern {
    public static void main(String[] args) {
        int n = 4;  // Maximum number for the diamond pattern

        // Loop to print the upper half of the diamond
        for (int i = 1; i <= n; i++) {  // Loop for each row
            for (int j = 1; j <= i; j++) {  // Loop for each column in the current row
                System.out.print(i);  // Print the current row number
                if (j < i) System.out.print("*");  // Print '*' if not the last number in the row
            }
            System.out.println();  // Move to the next line after each row
        }

        // Loop to print the lower half of the diamond
        for (int i = n - 1; i >= 1; i--) {  // Loop for each row
            for (int j = 1; j <= i; j++) {  // Loop for each column in the current row
                System.out.print(i);  // Print the current row number
                if (j < i) System.out.print("*");  // Print '*' if not the last number in the row
            }
            System.out.println();  // Move to the next line after each row
        }
    }
}
            

Output:

1
2*2
3*3*3
4*4*4*4
3*3*3
2*2
1