Array Programs
Start with Array Programs
Learn array programs through an executable example, then connect the small demonstration to production code.
What you’ll learn
- Explain the main purpose of array programs.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
Arrays have fixed lengths as part of their types. This makes them useful for a known-size collection and for practicing indexed iteration.
The example finds a maximum without sorting or modifying the array, and handles the nonempty-array assumption explicitly.
Visualize how it works
Follow this diagram before executing the example. Check where a value or decision changes what runs next.
Run a complete Go example
This example is a complete program. Save it as main.go or paste it into the Go Playground.
Go code
package main
import "fmt"
func main() {
numbers := [5]int{7, 4, 12, 3, 9}
max := numbers[0]
for _, value := range numbers {
if value > max {
max = value
}
}
fmt.Println("Maximum:", max)
fmt.Println("Length:", len(numbers))
}
Output
Maximum: 12
Length: 5Trace what the program does
Initialization starts max at the first element. The loop replaces it when 12 is encountered; length remains 5.
Avoid common mistakes
- An array length is part of its type: [3]int and [5]int are different types.
- Do not read index zero of an empty slice; check its length first.
Try it yourself
Change the data and add minimum-value detection.
Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.
Check your understanding
What you should remember
You have practiced Array Programs in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.
Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.
Reaching the recap and completing the quizzes are separate milestones.