Course outline
Course / The terminal and the language

Add up a number's digits

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-04-digit-sum
cd 11-04-digit-sum
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 individual digits of a positive integer N, using a condition-only for loop with % and /.

Example If you needed to sum the digits of 203, the loop would peel off 3, then 0, then 2:

sum := 0
n := 203
for n > 0 {
	sum += n % 10
	n /= 10
}
// sum is now 5

Rules

  • Edit digitsum.go. DigitSum has a // TODO comment and a return line you will change.
  • Copy N into a local variable first; don't change N itself.
  • Use a condition-only for loop (just a keep-going question, no init or post part) that runs while that local variable is greater than 0.
  • On each pass, add the last digit with % 10 to a running sum, then remove that digit with /= 10.
  • N can be 0, in which case the loop never runs and the sum stays 0.
  • Do not change var N int or the DigitSum function signature. Do not add imports.

What you'll practice Writing a condition-only for loop, and peeling digits off a number with % and /.

Run it

gonomicon fetch week-1/11-04-digit-sum
cd 11-04-digit-sum
gonomicon test
gonomicon submit

Hints

  1. Copy N into a local variable so you don't change N itself, then use a condition-only for loop that keeps going while that local variable is above 0.
  2. On each pass, add the last digit (n % 10) to your total, then drop that digit with integer division (n /= 10).
  3. sum := 0 n := N for n > 0 { sum += n % 10 n /= 10 } return sum

Something wrong with this lesson? Report a problem