Before the Lab
Study for the Python Quiz
The first half of the lab will be a Python quiz
~/cs2613/labs/L18// Our first program will print the classic "hello world"
// message. Here's the full source code.
package main
import "fmt"
func main() {
fmt.Println("hello world")
}
Running go code is a bit more complicated than the other languages we studied so far.
# To run the program, put the code in `hello-world.go` and
# use `go run`.
$ go run hello-world.go
hello world
# Sometimes we'll want to build our programs into
# binaries. We can do this using `go build`.
$ go build hello-world.go
$ ls
hello-world hello-world.go
# We can then execute the built binary directly.
$ ./hello-world
hello world
# Now that we can run and build basic Go programs, let's
# learn more about the language.
// `for` is Go's only looping construct. Here are
// some basic types of `for` loops.
package main
import "fmt"
func main() {
// The most basic type, with a single condition.
i := 1
for i <= 3 {
fmt.Println(i)
i = i + 1
}
// A classic initial/condition/after `for` loop.
for j := 0; j < 3; j++ {
fmt.Println(j)
}
// Another way of accomplishing the basic "do this
// N times" iteration is `range` over an integer.
for i := range 3 {
fmt.Println("range", i)
}
// `for` without a condition will loop repeatedly
// until you `break` out of the loop or `return` from
// the enclosing function.
for {
fmt.Println("loop")
break
}
// You can also `continue` to the next iteration of
// the loop.
for n := range 6 {
if n%2 == 0 {
continue
}
fmt.Println(n)
}
}
Modify the above example so that the output of each loop is reversed. For those involving range, modify the Println statement.
% go run for.go
3
2
1
3
2
1
range 2
range 1
range 0
loop
5
3
1
// Branching with `if` and `else` in Go is
// straight-forward.
package main
import "fmt"
func main() {
// Here's a basic example.
if 7%2 == 0 {
fmt.Println("7 is even")
} else {
fmt.Println("7 is odd")
}
// You can have an `if` statement without an else.
if 8%4 == 0 {
fmt.Println("8 is divisible by 4")
}
// Logical operators like `&&` and `||` are often
// useful in conditions.
if 8%2 == 0 || 7%2 == 0 {
fmt.Println("either 8 or 7 are even")
}
// A statement can precede conditionals; any variables
// declared in this statement are available in the current
// and all subsequent branches.
if num := 9; num < 0 {
fmt.Println(num, "is negative")
} else if num < 10 {
fmt.Println(num, "has 1 digit")
} else {
fmt.Println(num, "has multiple digits")
}
}
// Note that you don't need parentheses around conditions
// in Go, but that the braces are required.
Use the example above, along with a for loop, to write the "Fizzbuzz" example
% go run fizz-buzz.go
Fizzbuzz
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
Fizzbuzz
16
17
Fizz
19