Course outline
Course / The terminal and the language

Add them all up

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/11-01-sum-one-to-n
cd 11-01-sum-one-to-n
gonomicon submit

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

Goal 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. Sum has a // TODO comment and a return line you will change.
  • Declare an accumulator variable before the loop, starting at 0.
  • Use a three-component for loop that counts from 1 up through N, inclusive.
  • Add the loop variable to the accumulator on every pass.
  • N can be 0, in which case the loop should never run and the total stays 0.
  • Do not change var N int or the Sum function 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

  1. Declare an accumulator before the loop, starting at 0, then use a three-component for loop counting from 1 up through N.
  2. Inside the loop, add the loop variable to the accumulator on every pass: total += i. Return total once the loop ends.
  3. total := 0 for i := 1; i <= N; i++ { total += i } return total

Something wrong with this lesson? Report a problem