⚡ TL;DR
Print the magic square pattern in Go with working code and output. Full implementation, sample run, and complexity analysis included.
The Magic Square pattern is a classic loop exercise. Here’s the complete implementation in Go with working code and output.
Pattern to Print
17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9Implementation
package main
import (
"fmt"
"strings"
)
func main() {
n := 5
grid := make([][]int, n)
for i := range grid {
grid[i] = make([]int, n)
}
i, j := 0, n/2
for num := 1; num <= n*n; num++ {
grid[i][j] = num
ni, nj := (i-1+n)%n, (j+1)%n
if grid[ni][nj] != 0 {
ni, nj = (i+1)%n, j
}
i, j = ni, nj
}
for _, row := range grid {
parts := make([]string, len(row))
for k, v := range row {
parts[k] = fmt.Sprintf("%2d", v)
}
fmt.Println(strings.Join(parts, " "))
}
}Output
17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9How It Works
The Siamese method places consecutive numbers by moving up-right each step; when the target cell is already filled (or you wrap past an edge), drop one row instead. Every row, column, and both main diagonals then sum to the same magic constant, n(n²+1)/2.
Practice Variations
- Try printing the pattern with a different character (e.g.,
#or+) - Modify the code to accept the pattern size as user input
- Combine this pattern with its inverse to create a more complex shape
Complexity
- Time: O(n²) — the grid or line count grows quadratically
- Space: O(n²) — the grid is stored before printing
FAQ
How do you print the Magic Square pattern in Go?
Use nested loops: the outer loop walks through the rows while the inner loop prints the characters or values for each row. The complete Go implementation with expected output is shown in the sections above.
What is the time complexity of the Magic Square pattern in Go?
The time complexity is O(n²) and the space complexity is O(n²), since the pattern is built on a grid that is filled first and then printed row by row.
Happy coding!

Written by Mihir Pipermitwala
Senior Full Stack Consultant & Mobile Engineering Specialist building user-focused applications in healthcare with Flutter, Dart and React Native. I write about what I actually build and test — every tutorial here comes from real project work.
More about Mihir →