Course / The terminal and the language
Collect the first N even numbers
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-03-first-n-even-numbers
cd 11-03-first-n-even-numbers
gonomicon submitGoal
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.EvensListhas a// TODOcomment and a return line you will change. - If
Nis0or less, return""immediately. - Otherwise, count upward from
1with an infiniteforloop. - On each number, check it with
%2: if it's odd,continueto 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,breakout of the loop. - Do not change
var N intor theEvensListfunction signature.strconvis 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
- 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.
- 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.
- 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