Spiral Triangle of Numbers

This program prints a triangular spiral of numbers.

Problem Statement

Write a Java program that prints a triangle of 5 rows filled with numbers in spiral order.

Source Code

1 public class SpiralTriangleNumbers {
2 public static void main(String[] args) {
3 int n=5;
4 int[][] arr=new int[n][n];
5 int num=1;
6 for(int i=0;i<n;i++){
7 for(int j=0;j<=i;j++){
8 arr[i][j]=num++;
9 }
10 }
11 for(int i=0;i<n;i++){
12 for(int j=0;j<=i;j++){
13 System.out.print(arr[i][j]+" ");
14 }
15 System.out.println();
16 }
17 }
18 }

Program Output

1 
2 3 
4 5 6 
7 8 9 10 
11 12 13 14 15 

Explanation

A running counter num fills a triangular section of the matrix row by row, so the triangle is filled with a straightforward sequential progression rather than a boundary-based spiral.

Quick Links to Explore