Half Diamond Star Pattern
Program to Print Half Diamond Star Pattern
PRINTING PATTERN:
* ** *** **** *** ** *
PREREQUISITE:
Basic knowledge of Java language and loops.
ALGORITHM:
1. Take the number of rows as input from the user (height of the upper half of the diamond) and store it in a variable ('n').
2. Run a loop 'n' times to print the upper half of the diamond (i=1 to i<=n).
3. For each row, print spaces for alignment and then print stars equal to the current row number.
4. Run another loop 'n-1' times to print the lower half of the diamond (i=n-1 to i>0).
5. For each row, print spaces for alignment and then print stars equal to the current row number.
6. Move to the next line after each row has been printed.
Code in Java:
import java.util.Scanner; public class HalfDiamondPattern { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Enter the number of rows for the half diamond:"); int n = scanner.nextInt(); // Taking input for number of rows // Upper half of the diamond for (int i = 1; i <= n; i++) { // Print spaces for alignment for (int j = n - i; j > 0; j--) { System.out.print(" "); // Printing spaces } // Print stars for each row for (int j = 1; j <= i; j++) { System.out.print("*"); // Printing stars } System.out.println(); // New line after each row } // Lower half of the diamond for (int i = n - 1; i > 0; i--) { // Print spaces for alignment for (int j = n - i; j > 0; j--) { System.out.print(" "); // Printing spaces } // Print stars for each row for (int j = 1; j <= i; j++) { System.out.print("*"); // Printing stars } System.out.println(); // New line after each row } scanner.close(); } }
Output:
Enter the number of rows for the half diamond: 4 * ** *** **** *** ** *