Course outline
Course / The terminal and the language

Sum everything

Lab

How to fetch and submit this lab

Once: install the tool and connect your account.

curl -fsSL https://gonomicon.com/install.sh | sh
gonomicon login

Each lab: download it, edit the file named in the instructions, then submit.

gonomicon fetch week-1/12-05-sum-all
cd 12-05-sum-all
gonomicon submit

Go installed? gonomicon test runs the visible test on your computer first. Submitting also runs hidden checks on our server.

Goal Write Sum, a variadic function that adds up any number of ints it is called with, returning 0 when it is called with none.

Example If you needed to multiply any number of ints together the same way (with 1 for none), you'd write:

func Product(nums ...int) int {
	product := 1
	for _, n := range nums {
		product *= n
	}
	return product
}

Rules

  • Edit sumall.go. Sum has a // TODO comment and a return line you will change.
  • Declare the parameter with the ... form: func Sum(nums ...int) int.
  • Declare an accumulator before the loop, starting at 0, and range over nums adding each value to it.
  • Called with no arguments at all, Sum should return 0.
  • Do not change the function's name or give it any other parameters.

What you'll practice Writing a variadic parameter with ..., and ranging over it with an accumulator.

Run it

gonomicon fetch week-1/12-05-sum-all
cd 12-05-sum-all
gonomicon test
gonomicon submit

Hints

  1. Declare the parameter with the ... form, like func Sum(nums ...int) int. Inside the function, nums behaves like a list of ints you can range over.
  2. Declare an accumulator before the loop, starting at 0, then range over nums adding each value to it. Called with nothing, the loop just runs zero times and the accumulator stays 0.
  3. func Sum(nums ...int) int { sum := 0 for _, n := range nums { sum += n } return sum }

Something wrong with this lesson? Report a problem