Java Online Compiler
Example: Diamond Pattern Printer in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// Diamond Pattern Printer import java.util.Scanner; // Main class containing the entry point of the program public class Main { public static void main(String[] args) { // Step 1: Initialize Scanner for user input Scanner scanner = new Scanner(System.in); System.out.print("Enter the number of rows for the upper half of the diamond (e.g., 5): "); int n = scanner.nextInt(); // n represents the height of the upper half (including middle) // Step 2: Print the Upper Half of the Diamond // This loop iterates for each row in the upper half, from 1 to n for (int i = 1; i <= n; i++) { // Step 2.1: Print leading spaces // The number of spaces decreases as 'i' increases for (int j = 1; j <= n - i; j++) { System.out.print(" "); } // Step 2.2: Print stars // The number of stars increases (2*i - 1) as 'i' increases for (int j = 1; j <= 2 * i - 1; j++) { System.out.print("*"); } // Step 2.3: Move to the next line after completing a row System.out.println(); } // Step 3: Print the Lower Half of the Diamond // This loop iterates for each row in the lower half, from n-1 down to 1 for (int i = n - 1; i >= 1; i--) { // Step 3.1: Print leading spaces // The number of spaces increases as 'i' decreases for (int j = 1; j <= n - i; j++) { System.out.print(" "); } // Step 3.2: Print stars // The number of stars decreases (2*i - 1) as 'i' decreases for (int j = 1; j <= 2 * i - 1; j++) { System.out.print("*"); } // Step 3.3: Move to the next line after completing a row System.out.println(); } // Step 4: Close the scanner to release resources scanner.close(); } }
Output
Clear
ADVERTISEMENTS