GO / CHAPTER 01
Values, functions, and loops
BeginnerTrace a small typed Go program with a clear function boundary.
By the end of this chapter
- Declare typed local values
- Return a function result
- Trace a bounded for loop
The idea
Start here with arithmetic and basic programming ideas. A Go executable belongs to package main and starts in its main function. Local short declarations use :=, while assignments to existing variables use =. A declared variable receives its type’s zero value if no initializer is provided. Function signatures specify argument and result types so callers can see what values cross the boundary.
Go uses for for its looping forms. A loop with initialization, condition, and post statement checks the condition before each iteration. Keep an accumulator outside the body when it must survive between iterations. Integer division produces an integer quotient, so use floating point operands deliberately when a fractional result is required. Trace the condition and update separately to avoid counting an extra iteration.
package main
import "fmt"
func sumTo(n int) int {
total := 0
for i := 1; i <= n; i++ { total += i }
return total
}
func main(){fmt.Println(sumTo(4))}10
The loop adds one through four, then exits when i becomes five. The helper returns the accumulated integer.
Try it yourself
Write a function returning the sum of integers from zero up to but excluding n.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
CHECK YOUR UNDERSTANDING