Course outline
Course / The terminal and the language

Collect the first N even numbers

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-03-first-n-even-numbers
cd 11-03-first-n-even-numbers
gonomicon submit

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

Goal Build a space-separated string of the first N positive even numbers by counting upward and skipping odd numbers with continue, stopping with break once N have been collected.

Example If you needed the first N positive multiples of 3 the same way, you'd write:

result := ""
count := 0
for i := 1; ; i++ {
	if i%3 != 0 {
		continue
	}
	if count > 0 {
		result += " "
	}
	result += strconv.Itoa(i)
	count++
	if count == N {
		break
	}
}

Rules

  • Edit evens.go. EvensList has a // TODO comment and a return line you will change.
  • If N is 0 or less, return "" immediately.
  • Otherwise, count upward from 1 with an infinite for loop.
  • On each number, check it with %2: if it's odd, continue to the next number rather than computing even numbers directly.
  • When a number is even, add it to the result (joined with a single space between numbers) and increase a found-count.
  • Once the found-count reaches N, break out of the loop.
  • Do not change var N int or the EvensList function signature. strconv is already an allowed import.

What you'll practice Counting with an infinite for loop, skipping values with continue, and stopping with break once you have what you need.

Run it

gonomicon fetch week-1/11-03-first-n-even-numbers
cd 11-03-first-n-even-numbers
gonomicon test
gonomicon submit

Hints

  1. Handle N <= 0 first with an early return of "". Then count upward from 1 forever, and for each number check i % 2: if it's odd, continue to the next one.
  2. When a number is even, append it to your result (with a space before it if it isn't the first one) and bump a found-count. Once the found-count equals N, break.
  3. if N <= 0 { return "" } result := "" count := 0 for i := 1; ; i++ { if i%2 != 0 { continue } if count > 0 { result += " " } result += strconv.Itoa(i) count++ if count == N { break } } return result

Something wrong with this lesson? Report a problem