Exercises
For-loop
Create a loop with the
for
construct. Make it loop10 times and print out the loop counter with thefmt
package.Rewrite the loop from 1 to use
goto
. The keywordfor
may not be used.Rewrite the loop again so that it fills an array and then prints that array to the screen.
Answer
- There are many possibilities. One solution could be:
package main
import "fmt"
func main() {
for i := 0; i < 10; i++ {
fmt.Println("%d", i)
}
}
Let’s compile this and look at the output.
% go build for.go
% ./for
0
1
.
.
.
9
- Rewriting the loop results in code that should look somethinglike this (only showing the
main
-function):
func main() {
i := 0 1
Loop: 2
if i < 10 {
fmt.Printf("%d\n", i)
i++
goto Loop 3
}
}
At 1 we define our loop variable. And at 2 we define a label and at 3 we jumpto this label.
- The following is one possible solution:
package main
import "fmt"
func main() {
var arr [10]int 1
for i := 0; i < 10; i++ {
arr[i] = i 2
}
fmt.Printf("%v", arr) 3
}
Here 1 we create an array with 10 elements.Which we then fill 2 one by one. And finally we print it 3 with %v
which letsGo to print the value for us. You could even do this in one fell swoop by using a composite literal:
fmt.Printf("%v\n", [...]int{0,1,2,3,4,5,6,7,8,9})
Average
- Write code to calculate the average of a
float64
slice. Ina later exercise you will make it into a function.
Answer
- The following code calculates the average.
sum := 0.0
switch len(xs) {
case 0: 1
avg = 0
default: 2
for _, v := range xs {
sum += v
}
avg = sum / float64(len(xs)) 3
}
Here at 1 we check if the length is zero and if so, we return 0.Otherwise we calculate the average at 2.We have to convert the value return from len
to a float64
to make the division work at 3.
FizzBuzz
- Solve this problem, called the Fizz-Buzz [fizzbuzz] problem:Write a program that prints the numbers from 1 to 100. But for multiplesof three print, “Fizz” instead of the number, and for multiples offive, print “Buzz”. For numbers which are multiples of both three andfive, print “FizzBuzz”.
Answer
- A possible solution to this problem is the following program.
package main
import "fmt"
func main() {
const (
FIZZ = 3 1
BUZZ = 5
)
var p bool 2
for i := 1; i < 100; i++ { 3
p = false
if i%FIZZ == 0 { 4
fmt.Printf("Fizz")
p = true
}
if i%BUZZ == 0 { 5
fmt.Printf("Buzz")
p = true
}
if !p { 6
fmt.Printf("%v", i)
}
fmt.Println()
}
}
Here 1 we define two constants to make our code more readable, see .At 2 we define a boolean that keeps track if we already printed something.At 3 we start our for-loop, see .If the value is divisible by FIZZ - that is, 3 - , we print “Fizz” 4.And at 5 we check if the value is divisble by BUZZ – that is, 5 – if so print“Buzz”. Note that we have also taken care of the FizzBuzz case.At 6, if printed neither Fizz nor Buzz printed, we print the value.