10 More Pattern Programs in Go — Spiral, Diamond & More

By Mihir Pipermitwala · 6 min read

⚡ TL;DR

10 pattern programs in Go — spiral matrix, hollow diamond, letter triangle, Fibonacci triangle, wave, plus sign, and more. Full code and output.

A follow-up to our Go pattern collection, this post covers 10 more patterns commonly asked in Go interviews. Each includes working code and output.


1. Spiral Matrix

Fill an n x n grid with numbers in spiral order.

Copy
1  2  3  4
12 13 14 5
11 16 15 6
10 9  8  7
Copy
package main

import "fmt"

func spiralMatrix(n int) {
	m := make([][]int, n)
	for i := range m {
		m[i] = make([]int, n)
	}

	num := 1
	top, bottom, left, right := 0, n-1, 0, n-1

	for top <= bottom && left <= right {
		for i := left; i <= right; i++ {
			m[top][i] = num
			num++
		}
		top++
		for i := top; i <= bottom; i++ {
			m[i][right] = num
			num++
		}
		right--
		for i := right; i >= left; i-- {
			m[bottom][i] = num
			num++
		}
		bottom--
		for i := bottom; i >= top; i-- {
			m[i][left] = num
			num++
		}
		left++
	}

	for _, row := range m {
		for _, v := range row {
			fmt.Printf("%2d ", v)
		}
		fmt.Println()
	}
}

func main() {
	spiralMatrix(4)
}

Output

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

2. Hollow Diamond

Diamond outline with stars.

Copy
  *
 * *
*   *
 * *
  *
Copy
package main

import "fmt"

func hollowDiamond(n int) {
	for i := 1; i <= n; i++ {
		for j := 0; j < n-i; j++ {
			fmt.Print(" ")
		}
		if i == 1 {
			fmt.Print("*")
		} else {
			fmt.Print("*")
			for j := 0; j < 2*i-3; j++ {
				fmt.Print(" ")
			}
			fmt.Print("*")
		}
		fmt.Println()
	}
	for i := n - 1; i >= 1; i-- {
		for j := 0; j < n-i; j++ {
			fmt.Print(" ")
		}
		if i == 1 {
			fmt.Print("*")
		} else {
			fmt.Print("*")
			for j := 0; j < 2*i-3; j++ {
				fmt.Print(" ")
			}
			fmt.Print("*")
		}
		fmt.Println()
	}
}

func main() {
	hollowDiamond(3)
}

Output

Copy
  *
 * *
*   *
 * *
  *

3. Letter Triangle

Rows of consecutive letters.

Copy
A
A B
A B C
A B C D
A B C D E
Copy
package main

import (
	"fmt"
	"strings"
)

func letterTriangle(n int) {
	for i := 0; i < n; i++ {
		var row []string
		for j := 0; j <= i; j++ {
			row = append(row, string(rune('A'+j)))
		}
		fmt.Println(strings.Join(row, " "))
	}
}

func main() {
	letterTriangle(5)
}

Output

Copy
A
A B
A B C
A B C D
A B C D E

4. Number Stair

Row i repeats the number i.

Copy
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
Copy
package main

import (
	"fmt"
	"strconv"
	"strings"
)

func numberStair(n int) {
	for i := 1; i <= n; i++ {
		var row []string
		for j := 0; j < i; j++ {
			row = append(row, strconv.Itoa(i))
		}
		fmt.Println(strings.Join(row, " "))
	}
}

func main() {
	numberStair(5)
}

Output

Copy
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5

5. Fibonacci Triangle

Fibonacci numbers continue across rows.

Copy
0
1 1
2 3 5
8 13 21 34
55 89 144 233 377
Copy
package main

import (
	"fmt"
	"strconv"
	"strings"
)

func fibonacciTriangle(n int) {
	a, b := 0, 1
	for i := 1; i <= n; i++ {
		var row []string
		for j := 0; j < i; j++ {
			row = append(row, strconv.Itoa(a))
			a, b = b, a+b
		}
		fmt.Println(strings.Join(row, " "))
	}
}

func main() {
	fibonacciTriangle(5)
}

Output

Copy
0
1 1
2 3 5
8 13 21 34
55 89 144 233 377

6. Binary Triangle

Alternating 1s and 0s.

Copy
1
0 1
1 0 1
0 1 0 1
1 0 1 0 1
Copy
package main

import (
	"fmt"
	"strconv"
	"strings"
)

func binaryTriangle(n int) {
	for i := 1; i <= n; i++ {
		var row []string
		for j := 1; j <= i; j++ {
			row = append(row, strconv.Itoa((1+i+j)%2))
		}
		fmt.Println(strings.Join(row, " "))
	}
}

func main() {
	binaryTriangle(5)
}

Output

Copy
1
0 1
1 0 1
0 1 0 1
1 0 1 0 1

7. Plus Sign

A + made of stars.

Copy
  *
  *
*****
  *
  *
Copy
package main

import "fmt"

func plusSign(n int) {
	mid := n / 2
	for i := 0; i < n; i++ {
		for j := 0; j < n; j++ {
			if i == mid || j == mid {
				fmt.Print("*")
			} else {
				fmt.Print(" ")
			}
		}
		fmt.Println()
	}
}

func main() {
	plusSign(5)
}

Output

Copy
  *
  *
*****
  *
  *

8. Hollow Pyramid

A pyramid with hollow inside.

Copy
    *
   * *
  *   *
 *     *
*********
Copy
package main

import "fmt"

func hollowPyramid(n int) {
	for i := 1; i <= n; i++ {
		for j := 0; j < n-i; j++ {
			fmt.Print(" ")
		}
		if i == n {
			for j := 0; j < 2*n-1; j++ {
				fmt.Print("*")
			}
		} else if i == 1 {
			fmt.Print("*")
		} else {
			fmt.Print("*")
			for j := 0; j < 2*i-3; j++ {
				fmt.Print(" ")
			}
			fmt.Print("*")
		}
		fmt.Println()
	}
}

func main() {
	hollowPyramid(5)
}

Output

Copy
    *
   * *
  *   *
 *     *
*********

9. X-Shape

Diagonals of stars forming an “X”.

Copy
*   *
 * *
  *
 * *
*   *
Copy
package main

import "fmt"

func xShape(n int) {
	for i := 0; i < n; i++ {
		for j := 0; j < n; j++ {
			if i == j || i+j == n-1 {
				fmt.Print("*")
			} else {
				fmt.Print(" ")
			}
		}
		fmt.Println()
	}
}

func main() {
	xShape(5)
}

Output

Copy
*   *
 * *
  *
 * *
*   *

10. Sandglass

An inverted triangle on top of a triangle.

Copy
*****
 ***
  *
 ***
*****
Copy
package main

import "fmt"

func sandglass(n int) {
	for i := n; i >= 1; i-- {
		for j := 0; j < n-i; j++ {
			fmt.Print(" ")
		}
		for k := 0; k < 2*i-1; k++ {
			fmt.Print("*")
		}
		fmt.Println()
	}
	for i := 2; i <= n; i++ {
		for j := 0; j < n-i; j++ {
			fmt.Print(" ")
		}
		for k := 0; k < 2*i-1; k++ {
			fmt.Print("*")
		}
		fmt.Println()
	}
}

func main() {
	sandglass(3)
}

Output

Copy
*****
 ***
  *
 ***
*****

Conclusion

These Go patterns complete the trifecta of pattern posts on the site. Combine them with the earlier unique patterns in Go post for a complete beginner’s reference.

Happy coding!

Mihir Pipermitwala

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 →
Scroll down to load comments...
Related Blogs
Unlocking Flutter's Potential: Best Practices for Writing Clean Code

Unlocking Flutter's Potential: Best Practices for Writing Clean Code

Unlock Flutter's potential with clean code. Learn best practices for writing maintainable Dart code, with examples and essential principles.

CLEAN CODECODE BEST PRACTICESCODE MAINTAINABILITYCODE ORGANIZATIONCODE READABILITY

June 02, 2023

Top 9 Local Databases for Flutter: Full Comparison

Top 9 Local Databases for Flutter: Full Comparison

Compare the best local databases for Flutter (Isar, Hive, Sqflite, ObjectBox, Realm, Drift, Floor, CBL, Sembast). Find pros, cons, and performance comparisons.

CODINGFLUTTERFLUTTER LOCAL DATABASESLEARN TO CODENOSQL

April 06, 2023

Related Tutorials
Essential Git Skills: How to Delete Remote Branches

Essential Git Skills: How to Delete Remote Branches

Keep your repository clean and organized. This guide walks you through how to delete both local and remote branches in Git, step by step.

BITBUCKETDELETE LOCAL BRANCHDELETE REMOTE BRANCHGITGIT BRANCH CLEANUP AUTOMATION

June 12, 2024

Show an Offline Message for No Internet in Flutter

Show an Offline Message for No Internet in Flutter

You have to use the 'Connectivity Flutter Package' to achieve this feature on your App. This package helps to know whether your device is online or offline.

CONNECTIVITY PLUSDEPENDENCIESFLUTTERFLUTTER DEVELOPMENTFLUTTER PACKAGES

April 09, 2024

Mastering TabBar & TabBarView in Flutter: A Complete Guide

Mastering TabBar & TabBarView in Flutter: A Complete Guide

Implement TabBar and TabBarView in Flutter step by step — customize tab indicators, enable scrollable tabs, and change tabs programmatically.

CODINGDEFAULT TAB CONTROLLERFLUTTERLEARN TO CODETAB CONTROLLER

July 26, 2023

File Manipulation in Flutter: Best Practices & Examples

File Manipulation in Flutter: Best Practices & Examples

Master Flutter file manipulation — permission management, directory handling, and practical read-write scenarios to elevate your app's file handling.

CODINGFLUTTERFLUTTER DEVELOPMENTFLUTTER FILE OPERATIONFLUTTER PATH PROVIDER

June 30, 2023

Related Recommended Services
Visual Studio Code for the Web

Visual Studio Code for the Web

Build with Visual Studio Code, anywhere, anytime, in your browser.

IDEVISUAL STUDIOVISUAL STUDIO CODEWEB
Renovate | Automated Dependency Updates

Renovate | Automated Dependency Updates

Renovate Bot keeps source code dependencies up-to-date using automated Pull Requests.

AUTOMATED DEPENDENCY UPDATESBUNDLERCOMPOSERGITHUBGO MODULES
Best XML Formatter and XML Beautifier

Best XML Formatter and XML Beautifier

Online XML Formatter will format xml data, helps to validate, and works as XML Converter. Save and Share XML.

XMLXML BEAUTIFIERXML CONVERTERXML FORMATXML FORMATTER
Kubecost | Kubernetes cost monitoring and management

Kubecost | Kubernetes cost monitoring and management

Kubecost started in early 2019 as an open-source tool to give developers visibility into Kubernetes spend. We maintain a deep commitment to building and supporting dedicated solutions for the open source community.

CLOUDKUBECOSTKUBERNETESOPEN SOURCESELF HOSTED
Related Recommended Stories
How GitHub reduced testing time for iOS apps with new runner features

How GitHub reduced testing time for iOS apps with new runner features

Learn how GitHub used macOS and Apple Silicon runners for GitHub Actions to build, test, and deploy our iOS app faster.

IOSGITHUBTESTINGRUNNER
5 ways to transform your workflow using GitHub Copilot and MCP

5 ways to transform your workflow using GitHub Copilot and MCP

Learn how to streamline your development workflow with five different MCP use cases.

AGENT MODECODING AGENTCOPILOTFIGMAGITHUB
One weird trick for powerful Git aliases

One weird trick for powerful Git aliases

Advanced Git Aliases

ALIASALIAS TEMPLATEATLASSIANBITBUCKETGIT
Awesome Python

Awesome Python

An opinionated list of awesome Python frameworks, libraries, software and resources

AWESOMEAWESOME PYTHONCOLLECTIONSGITHUBPYTHON
Related Recommended Tools
Find out what websites are built with - Wappalyzer

Find out what websites are built with - Wappalyzer

Find out the technology stack of any website. Create lists of websites and contacts by the technologies they use.

ADD ONSANALYTICSAPP STOREAPPLEBOOKING
Sourcetree | Free Git GUI for Mac and Windows

Sourcetree | Free Git GUI for Mac and Windows

A Git GUI that offers a visual representation of your repositories. Sourcetree is a free Git client for Windows and Mac.

GITGITHUBGITLABATLASSIANBITBUCKET
Related Recommended Videos