Skip to content
Tutorials Center
My learning

Topics

Lesson 142 of 147 Β· Practice and Review

Go Programs: 50 Classic Examples

50 classic Go programs you can run: primes, Fibonacci, palindromes, Roman numerals, sorting algorithms, maps, structs, interfaces, generics, JSON and goroutines.

Almost every programmer writes the same small programs while learning a language: is this number prime, reverse a string, count the words in a text, sort a list without calling sort, split work among workers. They are short enough to read in a minute, and each one trains a real skill. This page collects 50 of them for Go, all written from scratch in modern Go (1.22 to 1.27).

Every program is complete and runs as it is: press Run and our server compiles it and shows the output underneath. Change a number, break something on purpose and run it again. The programs that read input come with values in the Input box, so you can edit those too. Each example has a short explanation and a link to the lesson where the idea is taught in depth. If you would rather write these yourself first, try the practice exercises.

A few habits run through the whole page. Output is formatted with fmt.Printf verbs (see the cheat sheet). Where the standard library already solves the problem (slices.Sort, strings.Fields, strconv.FormatInt), the program usually shows the hand-written version next to it, because you learn from writing the algorithm and you should use the library in real code. Map iteration order in Go is random, so every program that prints a map sorts the keys first. And all programs run on one CPU with a five-second limit, so they use small inputs.

Numbers and input

These practice variables, operators, if, loops and reading input.

1. Sum and average of numbers

Reads every word from the Input box, skips what is not a number, and prints the count, the sum and the average. bufio.ScanWords splits on any whitespace, including line breaks.

Go 1. Sum and average

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

2. Even or odd

A number is even when n%2 == 0. Compare with zero, never with one: in Go the remainder keeps the sign of the left operand, so -7 % 2 is -1, and a test like n%2 == 1 would call -7 even. See Operators.

Go 2. Even or odd

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

3. FizzBuzz

The famous warm-up. Test the combined case first, or use a switch with no expression so the order of the cases is explicit. See switch.

Go 3. FizzBuzz

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

4. Factorial

An iterative version, a recursive one, and the limit of uint64: 21! does not fit, and Go integers wrap around silently. The math/big package has no such limit. See Recursion and Numbers.

Go 4. Factorial

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

5. Fibonacci

Each number is the sum of the two before it. The loop keeps just two variables. The second version is an iterator (iter.Seq) that produces the numbers lazily, so the caller decides how many to take.

Go 5. Fibonacci

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

6. Prime numbers

Trial division only needs to try divisors up to the square root. The sieve of Eratosthenes finds all primes below a limit by crossing out multiples. See for Loops.

Go 6. Primes by trial division and by sieve

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

7. GCD and LCM

Euclid's algorithm: the greatest common divisor of a and b is the same as that of b and a % b. The least common multiple follows from lcm = a / gcd * b (divide first, so the intermediate value stays small).

Go 7. GCD and LCM

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

8. Digit sum and reverse a number

Peel digits off with % 10 and / 10. Handling the sign separately avoids surprises with negative numbers.

Go 8. Digit sum and reversed number

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

9. Armstrong numbers

A number is an Armstrong number when it equals the sum of its digits, each raised to the power of the number of digits (153 = 1^3 + 5^3 + 3^3). The program counts the digits first, then tests every number from 100 to 9999.

Go 9. Armstrong numbers

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

10. Leap years

A year is a leap year if it is divisible by 4, except years divisible by 100, unless they are also divisible by 400. One boolean expression says it all. See Operators.

Go 10. Leap years

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Conversions and patterns

Basic Types, Type Conversion and Printing with fmt.

11. Decimal to binary and hexadecimal

The manual way: divide by the base and collect remainders, last digit first. The library way: strconv.FormatInt and strconv.ParseInt accept any base from 2 to 36.

Go 11. Number bases

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

12. The Collatz sequence

Start with any positive number. If it is even, halve it, otherwise triple it and add one. The conjecture says every start reaches 1. The program prints the steps and the highest value reached for a few starting numbers.

Go 12. Collatz sequence

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

13. Printing a pyramid

strings.Repeat makes pattern programs short: each row has spaces on the left and an odd number of stars.

Go 13. A pyramid and a diamond

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Strings

Strings are immutable byte sequences; characters are runes. See Strings, Bytes and Runes and strings, strconv and unicode.

14. Reverse a string

Reversing the bytes breaks every multi-byte character. Convert to []rune first, swap from both ends, and convert back.

Go 14. Reverse a string

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

15. Palindrome checker

Ignore case, spaces and punctuation: keep only letters and digits, lower-case them, and compare from both ends. Each line of the Input box is one test.

Go 15. Palindrome checker

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

16. Count vowels and consonants

Walk the string rune by rune, classify each letter, and ignore everything else. strings.ContainsRune keeps the vowel test readable.

Go 16. Vowels and consonants

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

17. Word frequency

Lower-case the text, split on anything that is not a letter or apostrophe, and count in a map. The result is sorted by count (highest first), then alphabetically, because a map has no order. See Maps and Sorting.

Go 17. Word frequency

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

18. Anagram checker

Two words are anagrams if they use the same letters the same number of times. Count the runes of the first word up, the runes of the second one down, and check that every counter ends at zero.

Go 18. Anagrams

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

19. Caesar cipher

Shift each letter by a fixed number of places, wrapping around the alphabet. The + 26) % 26 trick makes negative shifts (decryption) work, because Go's % can return negative values.

Go 19. Caesar cipher

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

20. Title case

Split into words with strings.Fields, upper-case the first rune of each word and lower-case the rest. Working with runes keeps accented letters correct.

Go 20. Capitalize every word

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

21. Run-length encoding

Compress runs of the same character: aaabcc becomes a3b1c2. Decoding reads a character and the number after it. Counting runs is a good exercise in tracking "the previous item".

Go 21. Run-length encoding

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

22. Roman numerals

A table of values and symbols from large to small, including the subtractive pairs (CM, XL, IV), turns an integer into Roman numerals greedily. Parsing goes the other way: a smaller symbol before a larger one is subtracted.

Go 22. Roman numerals

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Slices and arrays

These practice slices, slice internals and the slices package.

23. Minimum, maximum, sum and average

One pass keeps all four. Since Go 1.21 the builtins min and max compare values, and slices.Min and slices.Max search a whole slice.

Go 23. Min, max, sum, average

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

24. Remove duplicates

A map remembers what was already seen, and the output keeps the original order. struct{} as the value costs no memory. For sorted data, slices.Compact removes neighbors that are equal.

Go 24. Remove duplicates

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

25. Reverse and rotate

Reversing swaps from both ends. A rotation by k positions can be done with three reversals, without a second slice: reverse the first k, reverse the rest, then reverse everything.

Go 25. Reverse and rotate a slice

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

26. Merge two sorted slices

Keep one index per slice and always take the smaller front item. This is the "merge" step of merge sort, and it runs in linear time.

Go 26. Merge sorted slices

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

On a sorted slice, look at the middle and discard half of the remaining range each step. lo + (hi-lo)/2 avoids overflow in other languages and is a good habit. The library version is slices.BinarySearch.

Go 27. Binary search

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

28. Matrix transpose and product

A matrix is a slice of rows. A transpose swaps rows and columns; a product sums a[i][k] * b[k][j]. Allocate every row yourself, because make([][]int, n) only creates n nil rows.

Go 28. Matrices

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

29. Second largest value

Sorting would work but costs more than needed. One pass with two variables does it in linear time. The tricky part is the starting values and duplicates of the maximum.

Go 29. Second largest

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Maps

Maps store key-value pairs with fast lookup. Remember: iteration order is random, so sort the keys when you print.

30. Character frequency

Count runes in a map and print them in sorted order. slices.Sorted(maps.Keys(m)) is the idiom for ordered output.

Go 30. Character frequency

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

31. Group words by length

A map from key to slice groups items. Appending to a missing key works, because a missing key gives a nil slice, and append accepts nil.

Go 31. Group words by length

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

32. Two sum

Find two numbers in a slice that add up to a target. Checking every pair is quadratic. With a map from value to index, one pass is enough: for each number, ask whether its complement was seen.

Go 32. Two sum with a map

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

33. A small inventory

Map values are not addressable: inv["apple"].Qty++ does not compile when the value is a struct. The pattern is copy, modify, store back. A map of pointers is the alternative when records change often.

Go 33. Inventory with a map of structs

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Sorting and recursion

Sorting and Recursion. In real code use slices.Sort; the hand-written sorts teach how algorithms work.

34. Bubble sort and insertion sort

Bubble sort repeatedly swaps neighbors that are out of order. Insertion sort grows a sorted prefix, moving each new item left into place. Both are quadratic, fine for tiny inputs and great for learning. Counting comparisons shows that insertion sort usually does less work, and that both finish in n-1 comparisons on data that is already sorted.

Go 34. Bubble and insertion sort

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

35. Quicksort

Pick a pivot, move smaller items to its left and larger to its right, then sort both sides recursively. This in-place version uses the Lomuto partition with the last element as pivot.

Go 35. Quicksort

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

36. Merge sort

Split in half, sort each half recursively, merge the results. It always takes n log n steps and is stable, at the price of extra memory.

Go 36. Merge sort

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

37. Sort records by several keys

Sort people by age (oldest first), and by name when the ages are equal. cmp.Or returns the first comparison that is not zero, which makes multi-key comparisons short.

Go 37. Multi-key sort

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

38. Towers of Hanoi

Move n disks from one peg to another using a spare peg. To move n disks: move n-1 to the spare peg, move the biggest one, move the n-1 back on top. The recursion mirrors that sentence, and the minimum number of moves is 2^n - 1.

Go 38. Towers of Hanoi

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

39. All permutations

Backtracking: fix one item at the front, permute the rest, then undo the choice. For abc there are 3! = 6 permutations.

Go 39. Permutations by backtracking

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Structs, interfaces and generics

Structs, Interfaces, Errors and Generics.

40. Shapes behind an interface

Different types share one method, Area, and are used through the Shape interface. A type switch pulls out type-specific details when needed.

Go 40. Shapes and an interface

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

41. Bank account with errors

Money is stored in cents so there are no rounding surprises. Failures are returned as errors, one of them a sentinel error that callers can recognize with errors.Is even after it is wrapped with more context. See Wrapping Errors.

Go 41. A bank account

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

42. A generic stack and queue

One definition works for every element type. The stack uses a slice end as its top; the queue keeps a head index so removing from the front does not copy the whole slice. See Generic Types.

Go 42. Generic stack and queue

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

43. A linked list

Each node points to the next one. Reversing the list rewires the pointers one by one. The list implements fmt.Stringer, so Println prints it nicely. See Pointers.

Go 43. A singly linked list

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

44. Generic Map, Filter and Reduce

Three small generic functions replace many hand-written loops. Type parameters are inferred from the arguments, so the calls look like ordinary function calls. See Generics in Practice.

Go 44. Map, Filter and Reduce

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

45. Encode and decode JSON

Struct tags control the field names in JSON. Marshal turns a value into bytes, Unmarshal fills a value from bytes, and malformed input comes back as an error. See JSON.

Go 45. JSON round trip

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Concurrency

Goroutines, Channels, sync and Patterns. The programs print only results whose order is guaranteed, because the order in which goroutines run is not.

46. Sum in parallel chunks

Split a slice into chunks, add each chunk in its own goroutine and send the partial sums over a channel. A WaitGroup plus a closing goroutine tells the receiver when no more results come.

Go 46. Parallel sum

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

47. A worker pool

Three workers read jobs from one channel and write results to another. Results arrive in any order, so the program stores each result at its job number and prints them in order. See Concurrency Patterns.

Go 47. A worker pool

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

48. A pipeline

Each stage is a function that takes a channel and returns a channel: generate numbers, square them, keep the odd ones. Stages run concurrently and the last one drives the whole chain.

Go 48. A channel pipeline

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

49. A safe shared counter

A thousand goroutines add to one counter. Without protection the result is wrong (a data race). A sync.Mutex guards the update, and the atomic.Int64 type does the same without a lock. See sync and Atomics.

Go 49. Mutex and atomic counters

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

50. Timeouts with select

select waits for the first of several channels. Combined with time.After it gives any slow operation a deadline. The program races a fast job and a slow job against a 100 ms timeout.

Go 50. select with a timeout

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Check your understanding

Quick check Β· 4 questions

of 4 answered You scored / 4 Β· perfect!

  1. 1. Why does the string-reversing program convert to []rune before swapping?

    Go strings are UTF-8 bytes. One character may use up to four bytes, so swapping bytes corrupts non-ASCII text. A rune slice holds one code point per element.
  2. 2. A program counts words with a map and prints for w, c := range counts. Why do the examples sort the keys first?

    The Go runtime randomizes map iteration order on purpose. Sort the keys (for example with slices.Sorted(maps.Keys(m))) whenever output order matters.
  3. 3. In the worker pool, why are the results stored by job number before printing?

    The goroutine scheduler decides which worker runs when, so results can arrive in any order. Putting each result at its own index makes the output deterministic.
  4. 4. What does fmt.Println(factorial(21)) show when factorial returns a uint64 and multiplies in a loop?

    21! is larger than the biggest uint64. Go integer arithmetic wraps around without any error at run time, so use math/big when values can grow that large.

Summary

  • Small classic programs train the habits behind real Go: handling errors, choosing between a loop and a library call, and using runes for text.
  • Sort map keys before printing; iteration order is random.
  • Use []rune for character work, strings.Builder for assembling text, cmp.Or and slices.SortFunc for multi-key sorts.
  • Recursion, backtracking and divide and conquer fit naturally into small functions.
  • Goroutines need a way to finish (WaitGroup, closing channels) and tests that do not depend on scheduling order.
  • Move on to the practice exercises to write your own versions.

Next: Go Practice Exercises