Diamond Number-Star Pattern (Initialized)
Understanding the Problem
The goal is to print a diamond-shaped pattern where numbers are printed in increasing order in the upper half and then decreasing order in the lower half. Each number is followed by a star except for the last number in each row. The pattern starts from a specified initialized number.
Pattern Explanation
The pattern consists of two halves: the upper half where numbers increment and the lower half where numbers decrement.
2 3*3 4*4*4 3*3 2
Observations:
- The pattern consists of 5 rows.
- Numbers increment from 2 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 2.
Algorithm
The pattern follows these steps:
- Initialize a variable to determine the starting number (N).
- Loop through rows from 0 to (N - 2) to print the upper half of the diamond.
- For each row, calculate the current number as (N + row).
- Loop through columns (up to the current row number + 1) and print the current number.
- Print the number followed by '*' except for the last number in the row.
- After completing the upper half, loop through rows from (N - 2) down to 0 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 DiamondNumberStarPatternInitialized { public static void main(String[] args) { int n = 2; // Starting number for the diamond pattern int rows = 3; // Number of rows in the upper half // Loop to print the upper half of the diamond for (int i = 0; i < rows; i++) { // Loop for each row int currentNumber = n + i; // Calculate the current number for (int j = 0; j <= i; j++) { // Loop for each column in the current row System.out.print(currentNumber); // Print the current 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 = rows - 1; i > 0; i--) { // Loop for each row int currentNumber = n + i - 1; // Calculate the current number for (int j = 0; j < i; j++) { // Loop for each column in the current row System.out.print(currentNumber); // Print the current number if (j < 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 } } }
Output:
2 3*3 4*4*4 3*3 2