Go array programs work with a fixed-size list of values, such as the marks of five subjects or the sales of seven days. They teach indexing, loops and how Go copies data, which are skills you need for slices, maps and every algorithm after this. In this post, you will write fourteen array programs with their exact output, and then practice the array questions interviewers ask most.
This post builds on our Go loop programs, since every array program uses a loop. For the theory of arrays and slices together, read Go slices and arrays explained. We tested every program on Go 1.27.
What are Go Array Programs?
Go array programs store several values of one type in a numbered row of boxes. The size is part of the type, so [5]int and [6]int are different types. Each box has an index that starts at 0.
Think of an egg tray with exactly six holes. You cannot add a seventh egg, and each hole has a fixed position. An array works the same way: a fixed number of slots, each found by its position.
Why Go Array Programs Matter
In day-to-day Go, you will use slices more than arrays. Still, arrays sit underneath every slice, so understanding them makes slices much easier. Go array programs also appear in interviews as max, second largest and reverse questions.
- Fixed data: days of the week, months, RGB colours and chess boards have a fixed size.
- Speed: arrays live in one block of memory, so reading them is very fast.
- Interview basics: most “array” questions in other languages map to these programs.
How Go Array Programs Work
An array has a length that never changes. You read and write items with arr[i], where i goes from 0 to len(arr) - 1. When you assign an array to another variable, Go copies every item.

The table below shows the ways to create an array.
| Syntax | Result | Notes |
|---|---|---|
| var a [5]int | [0 0 0 0 0] | All zero values |
| b := [3]string{“a”, “b”, “c”} | [a b c] | Size and values given |
| c := […]int{4, 8, 15} | [4 8 15] | Go counts the size, 3 |
| d := [5]int{1: 10, 3: 30} | [0 10 0 30 0] | Set only some indexes |
| var grid [2][3]int | [[0 0 0] [0 0 0]] | Array of arrays |
Basic Go Array Programs
These first Go array programs read and total the items in an array.
Program 1: Create and Print an Array
package main
import "fmt"
func main() {
// Step 1: make an array of 5 whole numbers. Every box starts at 0.
var marks [5]int
// Step 2: put values into box 0 and box 4.
marks[0] = 78
marks[4] = 91
// Step 3: make an array of 3 words.
// := creates a variable and gives it a value in one go.
// [...] tells Go to count the items for you.
days := [...]string{"Mon", "Tue", "Wed"}
// len gives the number of boxes in the array.
fmt.Println(marks, len(marks))
fmt.Println(days, len(days))
// The last box is at index len - 1, because counting starts at 0.
fmt.Println("First day:", days[0], "Last day:", days[len(days)-1])
}
[78 0 0 0 91] 5
[Mon Tue Wed] 3
First day: Mon Last day: Wed
First, you make an array of five numbers, and Go fills every box with 0. Then you set box 0 and box 4, so the boxes you did not touch stay at 0. The last index is always len - 1.
Program 2: Print Each Item with Its Index
This easy program shows how a loop visits every box of an array, one by one.
package main
import "fmt"
func main() {
fruits := [4]string{"apple", "banana", "mango", "grape"}
// range gives you two things on each turn:
// the index (position) and the value in that box.
for index, fruit := range fruits {
fmt.Println("Box", index, "holds", fruit)
}
}
Box 0 holds apple
Box 1 holds banana
Box 2 holds mango
Box 3 holds grape
The range loop runs once for each box in fruits. On each turn, index is the position and fruit is the word stored there. So the loop prints four lines, from box 0 to box 3.
Program 3: Sum and Average
package main
import "fmt"
func main() {
marks := [5]int{78, 85, 92, 66, 81}
// Step 1: add every mark to total.
total := 0
// _ means "I do not need the index here".
for _, mark := range marks {
total += mark // same as total = total + mark
}
fmt.Println("Sum:", total)
// Step 2: divide by the count to get the average.
// float64 turns whole numbers into decimal numbers,
// so the division keeps the part after the point.
average := float64(total) / float64(len(marks))
// %.1f prints a decimal number with 1 digit after the point.
// \n moves to a new line.
fmt.Printf("Average: %.1f\n", average)
}
Sum: 402
Average: 80.4
The loop adds each mark to total, so total ends at 402. Then you turn both numbers into float64 before dividing. If you divide two whole numbers, Go drops the decimal part.
Program 4: Largest and Smallest
package main
import "fmt"
func main() {
temperatures := [7]int{31, 28, 35, 33, 26, 30, 34}
// Step 1: start both answers at the first temperature.
hottest := temperatures[0]
coolest := temperatures[0]
// Step 2: check the rest of the items.
// [1:] means "from index 1 to the end", so we skip the first item.
for _, temperature := range temperatures[1:] {
if temperature > hottest {
hottest = temperature
}
if temperature < coolest {
coolest = temperature
}
}
fmt.Println("Hottest:", hottest, "Coolest:", coolest)
}
Hottest: 35 Coolest: 26
You start both values at the first item, not at 0. Then each new temperature can replace hottest or coolest if it is bigger or smaller. If all temperatures were negative, starting at 0 would give the wrong maximum.
Program 5: Second Largest Element
This is a top interview question. You track the largest and second largest in one pass.
package main
import (
"fmt"
"math"
)
func main() {
numbers := [6]int{12, 45, 7, 45, 33, 9}
// math.MinInt is the smallest int Go can hold.
// Any real number will be bigger than it.
largest := math.MinInt
secondLargest := math.MinInt
for _, number := range numbers {
if number > largest {
// A new top value: the old top moves down to second place.
secondLargest = largest
largest = number
} else if number > secondLargest && number != largest {
// Bigger than second place, but not a copy of the top value.
secondLargest = number
}
}
fmt.Println("Largest:", largest, "Second largest:", secondLargest)
}
Largest: 45 Second largest: 33
When a number beats largest, the old largest drops to second place. The check number != largest skips the second 45, so the answer is the second distinct value. Ask the interviewer if duplicates should count.
Rearranging Go Array Programs
These Go array programs move items around inside the array.
Program 6: Reverse an Array in Place
package main
import "fmt"
func main() {
numbers := [6]int{1, 2, 3, 4, 5, 6}
// i starts at the front, j starts at the back.
i := 0
j := len(numbers) - 1
// Keep going until the two indexes meet in the middle.
for i < j {
// Swap the two items. Go sets both sides at the same time.
numbers[i], numbers[j] = numbers[j], numbers[i]
i++ // move the front index one step right
j-- // move the back index one step left
}
fmt.Println(numbers)
}
[6 5 4 3 2 1]
Two indexes start at the two ends of the array. On each turn, you swap their items and move both indexes one step toward the middle. The loop stops when they meet, so no extra array is needed.
Program 7: Rotate an Array Left by K
package main
import "fmt"
func main() {
numbers := [5]int{10, 20, 30, 40, 50}
steps := 2 // how many places to move left
var rotated [5]int
for i := range numbers {
// % gives the remainder after division.
// It wraps the position back to the start when it passes the end.
sourceIndex := (i + steps) % len(numbers)
rotated[i] = numbers[sourceIndex]
}
fmt.Println(rotated)
}
[30 40 50 10 20]
Each box in rotated takes the item that sits steps places ahead in numbers. For box 3, the source index is 5 % 5, which is 0. So the remainder wraps the position around to the start.
Program 8: Separate Even and Odd Counts
package main
import "fmt"
func main() {
numbers := [8]int{3, 8, 15, 22, 7, 10, 41, 6}
evenCount := 0
oddCount := 0
for _, number := range numbers {
// A number is even when dividing by 2 leaves no remainder.
if number%2 == 0 {
evenCount++
} else {
oddCount++
}
}
fmt.Println("Even:", evenCount, "Odd:", oddCount)
}
Even: 4 Odd: 4
The loop checks each number with % 2. If the remainder is 0, the number is even, so you add one to evenCount. Otherwise you add one to oddCount.
Program 9: Find an Item and Its Position
This simple search looks at each box until it finds the value you want.
package main
import "fmt"
func main() {
cities := [5]string{"Pune", "Delhi", "Mumbai", "Chennai", "Goa"}
target := "Mumbai"
// -1 means "not found yet", because no real index is negative.
position := -1
for index, city := range cities {
if city == target {
position = index
break // stop the loop, we found it
}
}
if position == -1 {
fmt.Println(target, "is not in the array")
} else {
fmt.Println(target, "found at index", position)
}
}
Mumbai found at index 2
You start position at -1, which means “not found”. The loop compares each city with target, and break stops it at the first match. Then the program prints the index, or a “not in the array” message if nothing matched.
Program 10: Frequency of Each Element
When values are small, an array can count them faster than a map. Many Go array programs use this trick.
package main
import "fmt"
func main() {
ratings := [10]int{4, 5, 3, 5, 4, 5, 2, 4, 5, 1}
// count[1] holds how many 1-star ratings, count[5] how many 5-star ratings.
// Index 0 is not used.
var count [6]int
for _, rating := range ratings {
count[rating]++ // the rating itself picks the box to increase
}
// Print from 5 stars down to 1 star.
for star := 5; star >= 1; star-- {
// %d prints a whole number.
fmt.Printf("%d stars: %d\n", star, count[star])
}
}
5 stars: 4
4 stars: 3
3 stars: 1
2 stars: 1
1 stars: 1
The rating itself is the index into count. So a rating of 5 adds one to count[5]. This counting trick is the base of counting sort.
Copy and Compare Go Array Programs
Arrays are values in Go, which surprises people coming from Java or JavaScript. These Go array programs show what that means.
Program 11: Arrays are Copied on Assignment
package main
import "fmt"
func main() {
original := [3]int{1, 2, 3}
// Step 1: copy the whole array into a new variable.
copied := original // full copy of all 3 items
copied[0] = 100
fmt.Println("original:", original)
fmt.Println("copied:", copied)
// Step 2: take a pointer to the array.
// & gives the address of original, so no copy is made.
pointer := &original
pointer[1] = 200 // this changes original itself
fmt.Println("original after pointer change:", original)
}
original: [1 2 3]
copied: [100 2 3]
original after pointer change: [1 200 3]
copied := original copies all three items, so changing copied leaves original alone. A pointer holds the address of the array instead. So a change through pointer changes the real array.
Program 12: Compare Two Arrays
package main
import "fmt"
func main() {
first := [3]string{"go", "is", "fun"}
second := [3]string{"go", "is", "fun"}
third := [3]string{"go", "is", "hard"}
// == compares every item in order.
fmt.Println(first == second, first == third)
}
true false
Arrays of the same type can be compared with ==. Go checks every item in order. The last words differ in third, so that comparison is false.
Program 13: Merge Two Arrays
package main
import "fmt"
func main() {
odds := [3]int{1, 3, 5}
evens := [4]int{2, 4, 6, 8}
var merged [7]int
// [:] turns an array into a slice, which copy needs.
// copy(destination, source) copies items from source into destination.
copy(merged[:], odds[:])
// Start the second copy right after the first part.
copy(merged[len(odds):], evens[:])
fmt.Println(merged)
}
[1 3 5 2 4 6 8]
First, copy fills boxes 0 to 2 with the odd numbers. Then merged[len(odds):] starts at box 3, so the even numbers go after them. The result holds all seven items.
Program 14: Arrays as Map Keys
Because arrays are comparable, they can be map keys. Slices cannot.
package main
import "fmt"
func main() {
// A map links a key to a value.
// Here the key is [2]int, meaning {row, seat}.
seats := map[[2]int]string{
{1, 1}: "Asha",
{1, 2}: "Ravi",
}
// Look up row 1, seat 2.
fmt.Println(seats[[2]int{1, 2}])
fmt.Println(len(seats)) // number of entries in the map
}
Ravi
2
The key [2]int{1, 2} means row 1, seat 2. Go finds that key and returns “Ravi”. This pattern is handy for grids and coordinates.
Go Array Programs vs Slices
Most real Go code uses slices, so it helps to know when an array is the better fit. The diagram and table below compare them.

| Feature | Array | Slice |
|---|---|---|
| Size | Fixed, part of the type | Can grow with append |
| Assignment | Copies all items | Shares the same data |
| Compare with == | Yes | No, only with nil |
| Map key | Yes | No |
| Common use | Fixed data, keys, buffers | Almost everything else |
In short, use arrays when the size never changes or you need a map key. Use slices for lists that grow or shrink.
Common Mistakes in Go Array Programs
- Going past the end:
arr[len(arr)]panics, so the last index islen(arr) - 1. - Expecting shared data: assigning or passing an array copies it, so changes stay local.
- Mixing sizes:
[3]intand[4]intare different types and cannot be compared. - Starting max at 0: use the first item instead, or negative arrays give wrong answers.
- Using arrays for growing lists: you cannot append to an array, so use a slice.
Best Practices for Go Array Programs
- Use […] to let Go count the size, which avoids mistakes when you add items.
- Range over the array instead of manual indexes when you only read it.
- Pass a pointer or a slice to functions for large arrays, so Go does not copy them.
- Use small arrays as counters when values have a known small range.
- Prefer slices in APIs, since callers rarely have an exact-size array.
Go Array Programs Interview Questions and Answers
Interviewers use short Go array programs to test how arrays behave. Each program is complete, with real output from Go 1.27.
Basics Questions on Go Array Programs
Q1. What does this program print?
package main
import "fmt"
func main() {
var flags [4]bool // 4 booleans, all start as false
var names [2]string // 2 strings, all start as ""
fmt.Println(flags, len(names), names[0] == "")
}
[false false false false] 2 true
Every item starts at its type’s zero value. For a bool that is false, and for a string it is “”.
Q2. Why does this program not compile?
package main
import "fmt"
func main() {
numbers := [5]int{1, 2, 3, 4, 5}
fmt.Println(numbers[5]) // valid indexes are 0 to 4
}
invalid argument: index 5 out of bounds [0:5]
With a constant index, Go catches the mistake at compile time. With a variable index, the same mistake panics at run time instead.
Q3. What happens with a variable index that is too big?
package main
import "fmt"
func main() {
numbers := [3]int{1, 2, 3}
index := 3
fmt.Println(numbers[index]) // index 3 does not exist
}
panic: runtime error: index out of range [3] with length 3
Go cannot see the value of index while compiling. So the program starts, then stops with a panic when it reads box 3.
Q4. What does this program print?
package main
import "fmt"
// double gets its own copy of the array, so the caller's array does not change.
func double(numbers [3]int) {
for i := range numbers {
numbers[i] *= 2 // same as numbers[i] = numbers[i] * 2
}
}
// doublePtr gets a pointer (*) to the array, so it changes the real array.
func doublePtr(numbers *[3]int) {
for i := range numbers {
numbers[i] *= 2
}
}
func main() {
numbers := [3]int{1, 2, 3}
double(numbers)
fmt.Println(numbers)
doublePtr(&numbers) // & passes the address of numbers
fmt.Println(numbers)
}
[1 2 3]
[2 4 6]
double gets a copy, so the original does not change. doublePtr gets the address, so it changes the real array.
Type and Comparison Questions
Q5. Why does this program not compile?
package main
import "fmt"
func main() {
a := [3]int{1, 2, 3}
b := [4]int{1, 2, 3, 4}
fmt.Println(a == b) // different sizes mean different types
}
invalid operation: a == b (mismatched types [3]int and [4]int)
The size is part of the array type. So [3]int and [4]int are as different as int and string.
Q6. What does this program print?
package main
import "fmt"
func main() {
// 5: 1 puts 1 at index 5. The next values go to index 6 and 7.
numbers := [...]int{5: 1, 2, 3}
fmt.Println(len(numbers), numbers)
}
8 [0 0 0 0 0 1 2 3]
5: 1 puts 1 at index 5, and the next values follow at 6 and 7. So Go makes an array of length 8.
Q7. What does this program print?
package main
import "fmt"
func main() {
// 2 rows, and each row has 3 columns.
grid := [2][3]int{{1, 2, 3}, {4, 5, 6}}
fmt.Println(len(grid), len(grid[0]), grid[1][2])
}
2 3 6
A 2D array is an array of arrays. grid[1][2] is row 1, column 2, which holds 6.
Output Questions
Q8. What does this program print?
package main
import "fmt"
func main() {
numbers := [3]int{10, 20, 30}
for index, value := range numbers {
numbers[2] = 99 // change the real array during the loop
fmt.Print(index, ":", value, " ")
}
fmt.Println(numbers)
}
0:10 1:20 2:30 [10 20 99]
range over an array works on a copy made at the start. So value still reads 30, even though numbers[2] became 99.
Q9. What does this program print?
package main
import "fmt"
func main() {
numbers := [3]int{1, 2, 3}
view := numbers[:] // a slice that looks at the same boxes
view[0] = 50
fmt.Println(numbers, view)
}
[50 2 3] [50 2 3]
Slicing an array does not copy it. The slice points to the same memory, so a change through view also changes numbers.
Q10. What does this program print?
package main
import "fmt"
func main() {
// counts[0] is for 1-letter words, counts[1] for 2-letter words, and so on.
var counts [3]int
words := []string{"a", "bb", "a", "ccc", "bb", "a"}
for _, word := range words {
counts[len(word)-1]++
}
fmt.Println(counts)
}
[3 2 1]
The word length picks the box. There are three one-letter words, two two-letter words and one three-letter word.
Q11. When would you choose an array over a slice?
Choose an array when the size is fixed and known at compile time, such as a 3×3 board or a SHA-256 hash, which is [32]byte. Arrays are also needed as map keys, because slices are not comparable.
Q12. How do you find the length of an array without len?
You can count items with a range loop, but there is no reason to. len on an array is a constant worked out at compile time, so it costs nothing at run time.
Practice Task
This task combines several Go array programs from above. Write a program that takes an array of 10 daily step counts, prints the best and worst day number, and counts how many days were above 8,000 steps. Hint: track the index as well as the value when you find the max and min.
Official Resources
Quick Recap
- Go array programs use a fixed-size list where the size is part of the type.
- Indexes start at 0 and end at
len(arr) - 1. - Assigning or passing an array copies it, while a pointer or slice shares it.
- Arrays of the same type can be compared with
==and used as map keys. - Use arrays for fixed data, and slices for lists that change size.
What’s Next?
Next, we work with the most used collection in Go. Read Go slice programs with output, covering append, remove, merge and rotate. For the interview angle, see the Go slice interview questions.


