Course / The terminal and the language
Sum everything
How to fetch and submit this lab
Once: install the tool and connect your account.
curl -fsSL https://gonomicon.com/install.sh | sh
gonomicon loginEach 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 submitGoal
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.Sumhas a// TODOcomment 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 overnumsadding each value to it. - Called with no arguments at all,
Sumshould return0. - 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
- 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.
- 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.
- func Sum(nums ...int) int { sum := 0 for _, n := range nums { sum += n } return sum }