Drills — loops and conditions
Conditions and loops have to be written, not just read. Five tasks, from easy to harder. Write a function, run it on the examples, then compare with the solution.
1 (easy) — grade. Turn a score into a grade: 90+ → "A", 80+ → "B", 70+ → "C", else "F". Use a valueless switch (switch { case ... }).
grade(95) → "A" grade(83) → "B" grade(60) → "F"
func grade(score int) string {
switch {
case score >= 90:
return "A"
case score >= 80:
return "B"
case score >= 70:
return "C"
default:
return "F"
}
}
2 (easy) — sign. Return "positive", "negative" or "zero" (plain if).
sign(5) → "positive" sign(-2) → "negative" sign(0) → "zero"
func sign(n int) string {
if n > 0 {
return "positive"
}
if n < 0 {
return "negative"
}
return "zero"
}
3 (medium) — sumRange. Add the integers from lo to hi inclusive (a classic for).
sumRange(1, 5) → 15
func sumRange(lo, hi int) int {
total := 0
for i := lo; i <= hi; i++ {
total += i
}
return total
}
4 (medium) — fizzbuzz. From 1 to n: "Fizz" if divisible by 3, "Buzz" if by 5, "FizzBuzz" if by both, else the number itself. Return []string.
fizzbuzz(5) → [1 2 Fizz 4 Buzz]
func fizzbuzz(n int) []string {
out := []string{}
for i := 1; i <= n; i++ {
switch {
case i%15 == 0:
out = append(out, "FizzBuzz")
case i%3 == 0:
out = append(out, "Fizz")
case i%5 == 0:
out = append(out, "Buzz")
default:
out = append(out, fmt.Sprint(i))
}
}
return out
}
5 (harder) — digitSum. Add up a number's digits. Hint: n % 10 is the last digit, n /= 10 removes it.
digitSum(1234) → 10 digitSum(-99) → 18
func digitSum(n int) int {
if n < 0 {
n = -n
}
sum := 0
for n > 0 {
sum += n % 10
n /= 10
}
return sum
}
Tip. Call each function from
main(fmt.Println(grade(95))) and check it against the examples. These pure functions (no input, no state) are exactly what we'll test automatically withgo testin lesson 13.