Level: BeginnerGo Programs

Go Pattern Programs: Star, Number and Pyramid Patterns

Updated 17 min read
Go Pattern Programs featured image: star pyramid printed in a terminal

Go pattern programs print shapes such as triangles, pyramids and diamonds using stars, numbers or letters. They look simple, but they test exactly how well you control nested loops, which is why interviewers love them. In this post, you will write fourteen pattern programs with their exact output, and learn one trick that makes every pattern easier.

You need the nested loops from our Go loop programs post, so read it first if loops are new to you. We also use strings.Repeat from our Go strings guide. All programs were tested on Go 1.27.

What are Go Pattern Programs?

Go pattern programs use loops to print characters in rows and columns, so the output forms a shape. The outer loop picks the row, and the inner loop prints what goes in that row.

Think of a pattern as a grid on graph paper. Each row has some spaces on the left and some stars after them. Once you know how many of each a row needs, the code almost writes itself.

Why Go Pattern Programs Matter

Go pattern programs do not appear in real apps very often. However, they are one of the best ways to practise loop logic, because a single off-by-one mistake shows up right away in the shape.

  • Fresher interviews: star pyramids and Floyd’s triangle are very common.
  • Loop control: you learn how the outer and inner loop counters relate.
  • Debugging skill: a wrong shape tells you exactly which count is off.

How Go Pattern Programs Work

Every pattern answers two questions for row i: how many spaces come first, and how many symbols come after them. Write those two counts as small formulas in i, and the loops follow.

Go pattern programs diagram showing rows split into leading spaces and stars for a pyramid
For row i of an n-row pyramid, print n – i spaces, then 2i – 1 stars, then a new line.

The table below gives the formulas for the most common shapes, for row i from 1 to n.

PatternSpaces in row iSymbols in row i
Right triangle0i
Inverted right triangle0n – i + 1
Right-aligned trianglen – ii
Pyramidn – i2i – 1
Inverted pyramidi – 12(n – i) + 1

How to Solve Any Go Pattern Program in Four Steps

Before you write code, plan the shape on paper. This method works for almost all Go pattern programs, even ones you have never seen.

  1. Draw the output for a small size, such as n = 4, and number the rows from 1.
  2. Count each part of every row: leading spaces, symbols and any gap in the middle.
  3. Turn the counts into formulas in i, for example 4 – i spaces and 2i – 1 stars.
  4. Write one loop for the rows and print each part with strings.Repeat or an inner loop.

For example, take a right-aligned triangle with 4 rows. Row 1 has 3 spaces and 1 star, and row 4 has 0 spaces and 4 stars. So the spaces are n – i and the stars are i. With these two formulas, the program is just three lines long.

In short, the hard part of Go pattern programs is the counting, not the Go code. Once the formulas are right, the loops are always the same.

Star Go Pattern Programs

We start with star shapes, because they show the structure most clearly. The first one is the easiest of all, so it is a good warm-up.

Program 1: Solid Square, the Easiest of the Go Pattern Programs

Every row of a square has the same number of stars. So the inner loop does not depend on the row at all.

package main

import "fmt"

func main() {
    size := 4 // := creates a new variable and sets its value

    // The outer loop prints one row each time it runs.
    for i := 1; i <= size; i++ {
        // The inner loop prints the stars of the current row.
        for j := 1; j <= size; j++ {
            fmt.Print("* ") // Print does not move to a new line
        }
        fmt.Println() // Println with nothing inside just ends the row
    }
}
* * * *
* * * *
* * * *
* * * *

The outer loop runs 4 times, once for each row. Inside it, the inner loop prints 4 stars on the same line. Then fmt.Println() moves the cursor down, and the next row starts. Most Go pattern programs in this post follow this same two-loop shape.

Program 2: Right Triangle

Row i prints i stars. This version uses two loops, so you can see the structure.

package main

import "fmt"

func main() {
    rows := 5

    for i := 1; i <= rows; i++ {
        // Row i gets exactly i stars.
        for j := 1; j <= i; j++ {
            fmt.Print("* ")
        }
        fmt.Println() // end the row
    }
}
*
* *
* * *
* * * *
* * * * *

The only change from the square is the inner loop limit. It stops at i instead of the full size, so the rows grow by one star each. fmt.Println() ends each row.

Program 3: Inverted Right Triangle

Here we count the rows down instead of up. Also, strings.Repeat replaces the inner loop.

package main

import (
    "fmt"
    "strings"
)

func main() {
    rows := 5

    // Start at 5 and count down to 1.
    for i := rows; i >= 1; i-- {
        // strings.Repeat glues "* " together i times.
        line := strings.Repeat("* ", i)
        fmt.Println(line)
    }
}
* * * * *
* * * *
* * *
* *
*

strings.Repeat("* ", i) builds the row in one step. Since i goes down from 5 to 1, each row is one star shorter. Most Go developers prefer this, because it is shorter and easier to read.

Program 4: Right-Aligned Triangle

Now each row needs spaces before the stars, so the shape leans to the right.

package main

import (
    "fmt"
    "strings"
)

func main() {
    rows := 5

    for i := 1; i <= rows; i++ {
        // Step 1: the spaces push the stars to the right.
        spaces := strings.Repeat(" ", rows-i)
        // Step 2: row i has i stars.
        stars := strings.Repeat("*", i)
        // Step 3: join both parts with + and print them.
        fmt.Println(spaces + stars)
    }
}
    *
   **
  ***
 ****
*****

Row 1 gets 4 spaces and 1 star. As i grows, the spaces shrink and the stars grow by one. The + sign joins the two strings into one line.

Program 5: Pyramid

A pyramid needs n - i spaces and 2i - 1 stars in row i.

package main

import (
    "fmt"
    "strings"
)

func main() {
    n := 5 // n is the number of rows, as in the diagram

    for i := 1; i <= n; i++ {
        spaces := strings.Repeat(" ", n-i)  // n - i spaces
        stars := strings.Repeat("*", 2*i-1) // 2i - 1 stars
        fmt.Println(spaces + stars)
    }
}
    *
   ***
  *****
 *******
*********

Row 1 has 4 spaces and 1 star, while row 5 has no spaces and 9 stars. The odd star counts keep the pyramid centered.

Program 6: Inverted Pyramid

This is the pyramid turned upside down. The spaces now grow, and the stars shrink.

package main

import (
    "fmt"
    "strings"
)

func main() {
    rows := 5

    for i := 1; i <= rows; i++ {
        // Row 1 has no spaces, row 2 has one, and so on.
        spaces := strings.Repeat(" ", i-1)
        // Row 1 has the most stars, and each row has 2 fewer.
        stars := strings.Repeat("*", 2*(rows-i)+1)
        fmt.Println(spaces + stars)
    }
}
*********
 *******
  *****
   ***
    *

In row 1, the formula 2*(5-1)+1 gives 9 stars. Each next row loses 2 stars and gains 1 space. So the shape narrows evenly from both sides.

Program 7: Diamond

A diamond is a pyramid followed by an inverted pyramid that skips its widest row.

package main

import (
    "fmt"
    "strings"
)

// pyramidRow builds row number i of a pyramid that has the given number of rows.
func pyramidRow(rows, i int) string {
    spaces := strings.Repeat(" ", rows-i)
    stars := strings.Repeat("*", 2*i-1)
    return spaces + stars
}

func main() {
    rows := 4

    // Step 1: the top half, from row 1 down to the widest row.
    for i := 1; i <= rows; i++ {
        fmt.Println(pyramidRow(rows, i))
    }

    // Step 2: the bottom half, going back up without the widest row.
    for i := rows - 1; i >= 1; i-- {
        fmt.Println(pyramidRow(rows, i))
    }
}
   *
  ***
 *****
*******
 *****
  ***
   *

We moved the row logic into a function, so the two halves share it. The first loop prints rows 1 to 4. After that, the second loop prints rows 3, 2 and 1 again. This is a good habit for any repeated code.

Program 8: Hollow Square

Inside a hollow square, only the edges get a star. We check whether the current cell sits on the border.

package main

import "fmt"

func main() {
    size := 5

    for i := 1; i <= size; i++ {
        for j := 1; j <= size; j++ {
            // || means "or": first row, last row, first column or last column.
            onBorder := i == 1 || i == size || j == 1 || j == size

            if onBorder {
                fmt.Print("* ")
            } else {
                fmt.Print("  ") // two spaces keep the gap the same width
            }
        }
        fmt.Println()
    }
}
* * * * *
*       *
*       *
*       *
* * * * *

For every cell, onBorder is true or false. Border cells print a star, and inside cells print two spaces. That is why you need nested loops here, since each cell makes its own choice.

Number and Letter Go Pattern Programs

The same loops can print numbers or letters instead of stars. These Go pattern programs are just as common in interviews.

Program 9: Repeated Number Triangle

This easy number pattern prints the row number again and again. It is a nice first step before the trickier number shapes.

package main

import "fmt"

func main() {
    rows := 5

    for i := 1; i <= rows; i++ {
        // Print the row number i, exactly i times.
        for j := 1; j <= i; j++ {
            fmt.Print(i, " ") // print the number and then a space
        }
        fmt.Println()
    }
}
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5

The loops are the same as the right triangle in Program 2. The only change is that we print i instead of a star. So row 3 shows the number 3 three times.

Program 10: Number Triangle

Now each row counts from 1 instead of repeating one number.

package main

import "fmt"

func main() {
    rows := 5

    for i := 1; i <= rows; i++ {
        // j counts 1, 2, 3 ... up to the row number.
        for j := 1; j <= i; j++ {
            fmt.Print(j, " ")
        }
        fmt.Println()
    }
}
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

Here we print j, not i. Each row starts again at 1, because j resets at the start of every row.

Program 11: Floyd’s Triangle

In Floyd’s triangle, numbers keep counting across rows.

package main

import "fmt"

func main() {
    rows := 5
    number := 1 // lives outside the loops, so it never goes back to 1

    for i := 1; i <= rows; i++ {
        for j := 1; j <= i; j++ {
            fmt.Printf("%3d", number) // %3d prints the number in 3 columns
            number++                  // move to the next number
        }
        fmt.Println()
    }
}
  1
  2  3
  4  5  6
  7  8  9 10
 11 12 13 14 15

number lives outside both loops, so it never resets. Each cell prints it and then adds one. %3d keeps the columns lined up when numbers reach two digits.

Program 12: Pascal’s Triangle

Each number in Pascal’s triangle is the sum of the two numbers above it.

package main

import (
    "fmt"
    "strings"
)

func main() {
    rows := 6
    row := []int{1} // a slice (a growable list) that holds the current row

    for i := 0; i < rows; i++ {
        // Step 1: print spaces so the triangle is centered.
        fmt.Print(strings.Repeat(" ", (rows-i-1)*2))

        // Step 2: print every value in the current row.
        // range gives the index and value; _ ignores the index.
        for _, value := range row {
            fmt.Printf("%4d", value)
        }
        fmt.Println()

        // Step 3: build the next row, which is one value longer.
        nextRow := make([]int, len(row)+1) // make creates a slice filled with zeros
        nextRow[0] = 1                     // first value is always 1
        nextRow[len(row)] = 1              // last value is always 1
        for j := 1; j < len(row); j++ {
            nextRow[j] = row[j-1] + row[j] // add the two values above
        }
        row = nextRow
    }
}
             1
           1   1
         1   2   1
       1   3   3   1
     1   4   6   4   1
   1   5  10  10   5   1

We build each new row from the previous one. The first and last values are always 1, and every middle value adds its two neighbours above. At the end of the loop, nextRow becomes the current row.

Program 13: Alphabet Triangle

Letters are runes, so we can add to them just like numbers.

package main

import "fmt"

func main() {
    rows := 5

    for i := 0; i < rows; i++ {
        for j := 0; j <= i; j++ {
            // 'A' is a rune (a character code). 'A'+1 is 'B', and so on.
            letter := 'A' + rune(j)
            fmt.Printf("%c ", letter) // %c prints the rune as a letter
        }
        fmt.Println()
    }
}
A
A B
A B C
A B C D
A B C D E

'A' + rune(j) moves forward through the alphabet. %c prints the rune as a letter instead of a number. Both loops start at 0 here, so the first letter is 'A' + 0.

Program 14: Number Pyramid

Each row counts up to the row number and then back down.

package main

import (
    "fmt"
    "strings"
)

func main() {
    rows := 4

    for i := 1; i <= rows; i++ {
        // Step 1: spaces on the left.
        fmt.Print(strings.Repeat(" ", rows-i))

        // Step 2: count up from 1 to i.
        for j := 1; j <= i; j++ {
            fmt.Print(j)
        }

        // Step 3: count back down from i-1 to 1.
        for j := i - 1; j >= 1; j-- {
            fmt.Print(j)
        }
        fmt.Println()
    }
}
   1
  121
 12321
1234321

Each row counts up to i and back down. So it reads the same both ways, like a palindrome.

Nested Loops vs strings.Repeat in Go Pattern Programs

You have now seen both styles. The diagram and table below compare them.

Go pattern programs comparison of nested loops and strings.Repeat
Nested loops give cell-by-cell control, while strings.Repeat builds a full row in one call.
FeatureNested loopsstrings.Repeat
Code lengthLongerShorter
Control per cellFull, can use if per cellSame symbol for the whole run
Hollow shapesEasyHarder
ReadabilityGood for beginnersVery clear
SpeedMany small printsFewer, bigger prints

So use strings.Repeat for solid shapes, and nested loops when each cell needs its own decision, as in hollow shapes.

Common Mistakes in Go Pattern Programs

  • Wrong space count: draw the first and last rows on paper and work out the formula from them.
  • Missing new line: forgetting fmt.Println() after a row puts everything on one line.
  • Resetting the wrong counter: in Floyd’s triangle, the number must live outside the loops.
  • Mixing Print and Println: Println adds spaces between values, which can break alignment.
  • Even rows for a diamond: the middle row must be the widest, so plan the halves carefully.

Best Practices for Go Pattern Programs

  • Write the formula first, as spaces and symbols for row i.
  • Use strings.Repeat for solid runs of the same character.
  • Move a row into a function when you print it more than once.
  • Use Printf widths like %3d when numbers have different lengths.
  • Test with n = 1 and n = 2, because small sizes show off-by-one errors quickly.

Go Pattern Programs Interview Questions and Answers

Interviewers often show you one of these Go pattern programs and ask for the output. Each program below is complete, with real output from Go 1.27.

Output Questions on Go Pattern Programs

Q1. What does this program print?

package main

import "fmt"

func main() {
    for i := 1; i <= 3; i++ {
        for j := 1; j <= 3; j++ {
            fmt.Print(i * j) // row number times column number
        }
        fmt.Println()
    }
}
123
246
369

The inner loop multiplies the row number by 1, 2 and 3. So each row is a small times table.

Q2. What does this program print?

package main

import (
    "fmt"
    "strings"
)

func main() {
    for i := 3; i >= 1; i-- {
        hashes := strings.Repeat("#", i)   // i hash signs
        dots := strings.Repeat(".", 3-i)   // fill the rest with dots
        fmt.Println(hashes + dots)
    }
}
###
##.
#..

Every row is 3 characters wide. As i counts down, there are fewer # signs and more dots to fill the gap.

Q3. What does this program print?

package main

import "fmt"

func main() {
    for i := 1; i <= 4; i++ {
        for j := 1; j <= 4; j++ {
            if i == j {
                fmt.Print("\\") // "\\" is how you write one backslash
            } else {
                fmt.Print(".")
            }
        }
        fmt.Println()
    }
}
\...
.\..
..\.
...\

A cell is on the main diagonal when the row number equals the column number. The string "\\" prints one backslash.

Q4. What does this program print?

package main

import "fmt"

func main() {
    for i := 1; i <= 4; i++ {
        for j := 1; j <= 4; j++ {
            // % gives the remainder, so (i + j) % 2 is always 0 or 1.
            fmt.Print((i + j) % 2)
        }
        fmt.Println()
    }
}
0101
1010
0101
1010

(i + j) % 2 flips between 0 and 1 for each cell. This gives a chessboard pattern.

Q5. What does this program print?

package main

import "fmt"

func main() {
    for i := 4; i >= 1; i-- {
        // Start at the row number and count down to 1.
        for j := i; j >= 1; j-- {
            fmt.Print(j)
        }
        fmt.Println()
    }
}
4321
321
21
1

Both loops count down. The inner loop starts at the row number each time.

Q6. What does this program print?

package main

import "fmt"

func main() {
    for i := 0; i < 3; i++ {
        letter := 'a' + rune(i*2) // jump 2 letters each time
        fmt.Printf("%c\n", letter) // \n starts a new line
    }
}
a
c
e

Each step adds 2 to the rune, so it skips every other letter.

Logic Questions

Q7. How many stars does an n-row pyramid have in total?

Row i has 2i – 1 stars, and the sum of the first n odd numbers is n squared. So a 5-row pyramid has 25 stars.

Q8. What does this program print?

package main

import (
    "fmt"
    "strings"
)

func main() {
    total := 0

    for i := 1; i <= 5; i++ {
        row := strings.Repeat("*", 2*i-1)
        total += len(row) // len gives the number of characters; += adds it to total
    }
    fmt.Println(total)
}
25

The loop builds each pyramid row and adds its length to total. The rows have 1, 3, 5, 7 and 9 stars, which add up to 25. This confirms the answer to Q7 with code.

Q9. How do you print a hollow triangle?

Print a star only when the cell is on an edge. For a right triangle, that means the first column, the last column of the row (j == i) or the last row (i == n). Print a space for every other cell.

Q10. What does this program print?

package main

import "fmt"

func main() {
    size := 3

    for i := 1; i <= size; i++ {
        for j := 1; j <= size; j++ {
            if j <= i {
                fmt.Print("*")
            } else {
                fmt.Print("-")
            }
        }
        fmt.Println()
    }
}
*--
**-
***

Every row has 3 cells. Cells up to the row number get a star, and the rest get a dash.

Q11. How can you print a pattern faster for very large n?

Build each row with strings.Repeat or a strings.Builder, and wrap output in bufio.NewWriter(os.Stdout). Fewer, larger writes are much faster than thousands of single fmt.Print calls.

Q12. What does this program print?

package main

import "fmt"

func main() {
    for i := 1; i <= 3; i++ {
        width := i * 2
        // %*s takes the width from width, then pads "*" with spaces on the left.
        line := fmt.Sprintf("%*s", width, "*")
        fmt.Println(line)
    }
}
 *
   *
     *

%*s reads the width from an argument. So the width is 2, 4 and 6, and the star is pushed further right each row.

Practice Task

The butterfly is one of the harder Go pattern programs. Print it for n = 4: two right triangles that face each other, with spaces in the middle. Hint: row i needs i stars, then 2*(n-i) spaces, then i stars again, and the bottom half mirrors the top.

Official Resources

Quick Recap

  • Go pattern programs use an outer loop for rows and an inner loop or strings.Repeat for each row.
  • Work out two formulas for row i: the number of spaces and the number of symbols.
  • A pyramid row has n - i spaces and 2i - 1 stars.
  • Use nested loops with an if for hollow shapes and checkerboards.
  • Use %3d style widths when number patterns have different digit lengths.

What’s Next?

Next, we finish Level 2 with menus and calculators. Read Go switch programs with a calculator example. To revise strings before that, see our Go strings guide.