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

Square Spiral Star Pattern

The square spiral star pattern draws a single line of stars that winds inwards like a maze, with a one-cell gap between neighbouring turns. It looks simple, but it is one of the trickier star patterns to get right.

Quick answer: Walk from the top-left corner drawing stars. Before each step, check the next cell and the cell after it: move only if the next cell is inside and empty and the one after it is not already a star. Otherwise turn clockwise. Stop when two turns in a row give no move.

This program is part of the Spiral Patterns collection.

Table of contents8 sections
  1. Output
  2. How the square spiral star pattern 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

Square Spiral Star Pattern output

Output (9 × 9):

*********
        *
******* *
*     * *
* *** * *
* *   * *
* ***** *
*       *
*********
Square Spiral Star Pattern layout diagram, row by row (9 × 9)
How each row of the square spiral star pattern is built (9 × 9). Blue cells are printed characters; grey dots are spaces.

How the square spiral star pattern works

A spiral of numbers fills every cell, but a star spiral must leave a gap between its rings. The look-ahead does that: if two cells ahead there is already a star, stepping forward would close the gap, so the walk turns instead. Turning twice without moving means the line has nowhere left to go, which ends the drawing.

  1. Start with an empty n × n grid and a star in the top-left cell, facing right.
  2. Look at the next cell and the cell after it in the current direction.
  3. If the next cell is inside the grid, empty, and the cell after it is not a star, step forward and draw a star.
  4. Otherwise turn clockwise. If two turns in a row give no step, stop and print the grid.

Key takeaways

  • The look-ahead of two cells keeps a gap between the rings.
  • The walk turns clockwise whenever it would run into the edge or an earlier ring.
  • Two failed turns in a row mean the spiral is finished.
  • Odd sizes such as 9 or 11 give the neatest spirals.

Square Spiral Star Pattern in C

#include <stdio.h>

int main(void) {
    int n = 9;                                  /* an odd size gives the neatest spiral */
    char g[20][20];
    int dr[] = {0, 1, 0, -1};                   /* right, down, left, up */
    int dc[] = {1, 0, -1, 0};
    int r = 0, c = 0, d = 0;

    for (int i = 0; i < n; i++)
        for (int j = 0; j < n; j++)
            g[i][j] = ' ';
    g[0][0] = '*';
    for (;;) {
        int moved = 0;
        for (int turn = 0; turn < 2 && !moved; turn++) {
            int nr = r + dr[d], nc = c + dc[d];         /* the next cell */
            int ar = nr + dr[d], ac = nc + dc[d];       /* the cell after it */
            int inside = nr >= 0 && nr < n && nc >= 0 && nc < n;
            int blocked = ar >= 0 && ar < n && ac >= 0 && ac < n && g[ar][ac] == '*';
            if (inside && g[nr][nc] == ' ' && !blocked) {
                r = nr;
                c = nc;
                g[r][c] = '*';
                moved = 1;
            } else {
                d = (d + 1) % 4;
            }
        }
        if (!moved)
            break;
    }
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++)
            printf("%c", g[i][j]);
        printf("\n");
    }
    return 0;
}

Square Spiral Star Pattern in C++

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

int main() {
    int n = 9;                                  // an odd size gives the neatest spiral
    vector<string> g(n, string(n, ' '));
    int dr[] = {0, 1, 0, -1};                   // right, down, left, up
    int dc[] = {1, 0, -1, 0};
    int r = 0, c = 0, d = 0;

    g[0][0] = '*';
    for (;;) {
        bool moved = false;
        for (int turn = 0; turn < 2 && !moved; turn++) {
            int nr = r + dr[d], nc = c + dc[d];         // the next cell
            int ar = nr + dr[d], ac = nc + dc[d];       // the cell after it
            bool inside = nr >= 0 && nr < n && nc >= 0 && nc < n;
            bool blocked = ar >= 0 && ar < n && ac >= 0 && ac < n && g[ar][ac] == '*';
            if (inside && g[nr][nc] == ' ' && !blocked) {
                r = nr;
                c = nc;
                g[r][c] = '*';
                moved = true;
            } else {
                d = (d + 1) % 4;
            }
        }
        if (!moved)
            break;
    }
    for (const string &row : g)
        cout << row << endl;
    return 0;
}

Square Spiral Star Pattern in Java

public class StarSquareSpiral {
    public static void main(String[] args) {
        int n = 9;                                  // an odd size gives the neatest spiral
        char[][] g = new char[n][n];
        int[] dr = {0, 1, 0, -1};                   // right, down, left, up
        int[] dc = {1, 0, -1, 0};
        int r = 0, c = 0, d = 0;

        for (char[] row : g)
            java.util.Arrays.fill(row, ' ');
        g[0][0] = '*';
        while (true) {
            boolean moved = false;
            for (int turn = 0; turn < 2 && !moved; turn++) {
                int nr = r + dr[d], nc = c + dc[d];         // the next cell
                int ar = nr + dr[d], ac = nc + dc[d];       // the cell after it
                boolean inside = nr >= 0 && nr < n && nc >= 0 && nc < n;
                boolean blocked = ar >= 0 && ar < n && ac >= 0 && ac < n && g[ar][ac] == '*';
                if (inside && g[nr][nc] == ' ' && !blocked) {
                    r = nr;
                    c = nc;
                    g[r][c] = '*';
                    moved = true;
                } else {
                    d = (d + 1) % 4;
                }
            }
            if (!moved)
                break;
        }
        for (char[] row : g)
            System.out.println(new String(row));
    }
}

Square Spiral Star Pattern in Python

n = 9                                       # an odd size gives the neatest spiral
g = [[" "] * n for _ in range(n)]
dr = [0, 1, 0, -1]                          # right, down, left, up
dc = [1, 0, -1, 0]
r = c = d = 0

g[0][0] = "*"
while True:
    moved = False
    for turn in range(2):
        nr, nc = r + dr[d], c + dc[d]       # the next cell
        ar, ac = nr + dr[d], nc + dc[d]     # the cell after it
        inside = 0 <= nr < n and 0 <= nc < n
        blocked = 0 <= ar < n and 0 <= ac < n and g[ar][ac] == "*"
        if inside and g[nr][nc] == " " and not blocked:
            r, c = nr, nc
            g[r][c] = "*"
            moved = True
            break
        d = (d + 1) % 4
    if not moved:
        break
for row in g:
    print("".join(row))

Time and space complexity

The walk visits each cell at most once and each step costs constant work, so the program runs in O(n²) time with O(n²) memory for the grid.

Frequently asked questions

Why not use the formula approach of the number spirals?

The number spirals fill every cell, so they only need to know when a run ends. The star spiral has gaps, and the look-ahead is the simplest reliable way to keep them one cell wide.

What happens with an even n?

The spiral still draws, but it ends with a short stub near the centre instead of a clean turn.

How do I draw it anticlockwise?

Start in the top-right corner facing left and turn anticlockwise instead: use the directions left, down, right, up.

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 9 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.