New: 213 pattern programs with tested code in C, C++, Java and Python Explore patterns

Spiral Number Triangle

The spiral number triangle fills a right triangle with the numbers 1 to 15 in a spiral: down the slanted side, left along the base, up the first column, and round again into the middle.

Quick answer: Use the same walking idea as the square spiral but with three directions: down the diagonal (row + 1, column + 1), left along a row, and up a column. Only cells on or below the diagonal, column ≤ row, are allowed. Turn whenever the next cell is outside the triangle or already filled.

This program is part of the Spiral Patterns collection.

Table of contents8 sections
  1. Output
  2. How the spiral number triangle works
  3. Program in C
  4. Program in C++
  5. Program in Java
  6. Program in Python
  7. Time and space complexity
  8. Frequently asked questions

Spiral Number Triangle output

Output (n = 5):

  1
 12  2
 11 13  3
 10 15 14  4
  9  8  7  6  5
Spiral Number Triangle layout diagram, row by row (n = 5)
The numbers of the spiral number triangle laid out row by row (n = 5).

How the spiral number triangle works

A triangle has three sides, so the walk needs three directions instead of four. The rule for staying inside changes too: as well as the grid bounds, the next cell must satisfy column ≤ row. Everything else, write a number, look ahead, turn if blocked, is the same code that draws the square spirals.

  1. Fill an n × n grid with zeros and start at the top cell.
  2. For each value from 1 to n(n + 1)/2: write it, then try to step in the current direction.
  3. If the next cell is outside the triangle (column > row or off the grid) or already filled, turn to the next of the three directions.
  4. Print the lower triangle row by row.

Key takeaways

  • The triangle needs three directions: diagonal, left and up.
  • The extra test column ≤ row keeps the walk inside the triangle.
  • The triangle holds n(n + 1)/2 numbers: 15 for five rows.
  • The same walking code drives every spiral on this page; only the directions and limits change.

Spiral Number Triangle in C

#include <stdio.h>

int main(void) {
    int n = 5;
    int a[20][20] = {0};                    /* n can be up to 20 */
    int dr[] = {1, 0, -1};                  /* down the slope, left along the base, up the side */
    int dc[] = {1, -1, 0};
    int r = 0, c = 0, d = 0;

    for (int value = 1; value <= n * (n + 1) / 2; value++) {
        a[r][c] = value;
        for (int turn = 0; turn < 3; turn++) {   /* find the next free cell */
            int nr = r + dr[d], nc = c + dc[d];
            if (nr >= 0 && nr < n && nc >= 0 && nc < n && nc <= nr && a[nr][nc] == 0) {
                r = nr;
                c = nc;
                break;
            }
            d = (d + 1) % 3;
        }
    }

    for (int i = 0; i < n; i++) {
        for (int j = 0; j <= i; j++)
            printf("%3d", a[i][j]);
        printf("\n");
    }
    return 0;
}

Spiral Number Triangle in C++

#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;

int main() {
    int n = 5;
    vector<vector<int>> a(n, vector<int>(n, 0));
    int dr[] = {1, 0, -1};                  // down the slope, left along the base, up the side
    int dc[] = {1, -1, 0};
    int r = 0, c = 0, d = 0;

    for (int value = 1; value <= n * (n + 1) / 2; value++) {
        a[r][c] = value;
        for (int turn = 0; turn < 3; turn++) {   // find the next free cell
            int nr = r + dr[d], nc = c + dc[d];
            if (nr >= 0 && nr < n && nc >= 0 && nc < n && nc <= nr && a[nr][nc] == 0) {
                r = nr;
                c = nc;
                break;
            }
            d = (d + 1) % 3;
        }
    }

    for (int i = 0; i < n; i++) {
        for (int j = 0; j <= i; j++)
            cout << setw(3) << a[i][j];
        cout << endl;
    }
    return 0;
}

Spiral Number Triangle in Java

public class SpiralTriangle {
    public static void main(String[] args) {
        int n = 5;
        int[][] a = new int[n][n];
        int[] dr = {1, 0, -1};                  // down the slope, left along the base, up the side
        int[] dc = {1, -1, 0};
        int r = 0, c = 0, d = 0;

        for (int value = 1; value <= n * (n + 1) / 2; value++) {
            a[r][c] = value;
            for (int turn = 0; turn < 3; turn++) {   // find the next free cell
                int nr = r + dr[d], nc = c + dc[d];
                if (nr >= 0 && nr < n && nc >= 0 && nc < n && nc <= nr && a[nr][nc] == 0) {
                    r = nr;
                    c = nc;
                    break;
                }
                d = (d + 1) % 3;
            }
        }

        for (int i = 0; i < n; i++) {
            for (int j = 0; j <= i; j++)
                System.out.print(String.format("%3d", a[i][j]));
            System.out.println();
        }
    }
}

Spiral Number Triangle in Python

n = 5
a = [[0] * n for _ in range(n)]
dr = [1, 0, -1]                          # down the slope, left along the base, up the side
dc = [1, -1, 0]
r = c = d = 0

for value in range(1, n * (n + 1) // 2 + 1):
    a[r][c] = value
    for turn in range(3):              # find the next free cell
        nr, nc = r + dr[d], c + dc[d]
        if 0 <= nr < n and 0 <= nc < n and nc <= nr and a[nr][nc] == 0:
            r, c = nr, nc
            break
        d = (d + 1) % 3

for i in range(n):
    for j in range(i + 1):
        print(f"{a[i][j]:3d}", end="")
    print()

Time and space complexity

Each of the n(n + 1)/2 cells is filled once with at most three direction checks, so the program runs in O(n²) time with O(n²) memory for the grid.

Frequently asked questions

Where does the last number end up?

For n = 5, 15 is on row 4, column 2, the last free cell inside the second loop of the spiral.

Can I spiral the other way?

Yes. Use the directions down the first column, right along the base and up the diagonal. The spiral then runs anticlockwise.

Both use the numbers 1 to n(n + 1)/2 in a right triangle. Floyd’s triangle fills them row by row; this one follows the edges inwards.

This tutorial was drafted with AI assistance. Spotted a mistake? Tell us and we fix it. Read our editorial policy.

Quick check: can you predict the output?

Answer from the code, then check. Every answer comes from the real output above.

Pattern 8 of 14 in Spiral Patterns

 

Still stuck? Ask AI to explain this code

Opens your favourite AI with this page, ready to explain every loop step by step.

Authored by

Ghanendra Yadav runs Pattern Programs from Bangalore, India. The site started in 2020 to help students practise loops and logic through pattern programs in C, C++, Java and Python. Every program published here is compiled and run before it goes live, and the output shown is the real output.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.