Numeric Spiral Diamond

This program prints a diamond filled with sequential numbers in spiral-like growth.

Problem Statement

Write a Java program that prints a diamond pattern filled with sequential numbers up to 5 rows.

Source Code

1 public class NumericSpiralDiamond {
2 public static void main(String[] args) {
3 int n = 5, num=1;
4 for(int i=1; i<=n; i++) {
5 for(int j=i; j<n; j++) System.out.print(" ");
6 for(int j=1; j<=2*i-1; j++) System.out.print(num++ + " ");
7 System.out.println();
8 }
9 for(int i=n-1; i>=1; i--) {
10 for(int j=i; j<n; j++) System.out.print(" ");
11 for(int j=1; j<=2*i-1; j++) System.out.print(num++ + " ");
12 System.out.println();
13 }
14 }
15 }

Program Output

    1     
   2 3 4   
  5 6 7 8 9 
 10 11 12 13 14 15 16 
17 18 19 20 21 22 23 24 25 
 26 27 28 29 30 31 32 
  33 34 35 36 37 
   38 39 40 
    41 

Explanation

The variable num continuously increments and is printed instead of a fixed symbol as the diamond shape is built through increasing then decreasing rows, so the diamond becomes filled with a continuous sequence of numbers.

Quick Links to Explore