ProgramGuru

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.

Visual explanation for example arraysKeep track of the best value seen so far.Fixed arrayStep 1Initialize maxStep 2Compare valuesStep 3Print maximumStep 4Keep track of the best value seen so far.
Keep track of the best value seen so far.

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: 5

Trace 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

Which statement is true of a Go array?
Choose one answer. You can try again.

Answer and explanation

Its length is part of its type

Correct. Initialization starts max at the first element.

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.

    Next lesson: Slice Programs →