Course / The terminal and the language
Add them all up
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/11-01-sum-one-to-n
cd 11-01-sum-one-to-n
gonomicon submitGoal
Sum the whole numbers from 1 to N using a three-component for loop and an accumulator.
Example
If you needed to sum every number from 1 to 3, the loop would add 1, then 2, then 3:
total := 0
for i := 1; i <= 3; i++ {
total += i
}
// total is now 6
Rules
- Edit
sum.go.Sumhas a// TODOcomment and a return line you will change. - Declare an accumulator variable before the loop, starting at
0. - Use a three-component
forloop that counts from1up throughN, inclusive. - Add the loop variable to the accumulator on every pass.
Ncan be0, in which case the loop should never run and the total stays0.- Do not change
var N intor theSumfunction signature. Do not add imports.
What you'll practice
Writing a three-component for loop, and building up a total with an accumulator declared outside the loop.
Run it
gonomicon fetch week-1/11-01-sum-one-to-n
cd 11-01-sum-one-to-n
gonomicon test
gonomicon submit
Hints
- Declare an accumulator before the loop, starting at 0, then use a three-component for loop counting from 1 up through N.
- Inside the loop, add the loop variable to the accumulator on every pass: total += i. Return total once the loop ends.
- total := 0 for i := 1; i <= N; i++ { total += i } return total