Java Online Compiler
Example: Number Diamond Pattern in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// Number Diamond Pattern import java.util.Scanner; // Main class containing the entry point of the program public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // Step 1: Get user input for the number of rows System.out.print("Enter the number for the diamond (e.g., 4): "); int n = scanner.nextInt(); // Step 2: Print the upper half of the diamond (including the middle row) for (int i = 1; i <= n; i++) { // Print leading spaces for (int j = 1; j <= n - i; j++) { System.out.print(" "); } // Print increasing numbers for (int j = 1; j <= i; j++) { System.out.print(j); } // Print decreasing numbers for (int j = i - 1; j >= 1; j--) { System.out.print(j); } System.out.println(); // Move to the next line } // Step 3: Print the lower half of the diamond for (int i = n - 1; i >= 1; i--) { // Print leading spaces for (int j = 1; j <= n - i; j++) { System.out.print(" "); } // Print increasing numbers for (int j = 1; j <= i; j++) { System.out.print(j); } // Print decreasing numbers for (int j = i - 1; j >= 1; j--) { System.out.print(j); } System.out.println(); // Move to the next line } scanner.close(); // Close the scanner } }
Output
Clear
ADVERTISEMENTS