2. Logic and Loops
Activity 2.01: Implementing FizzBuzz
Solution:
- Define
package
and includeimport
:package main import ( "fmt" "strconv" )
- Create the
main
function:func main() {
- Create a
for
loop that starts at 1 and loops untili
gets to 100:for i := 1; i <= 100; i++{
- Initialize a string variable that will hold the output:
out := ""
- Using module logic to check for divisibility,
if
i
is divisible by 3, then add"Fizz"
to theout
string:if i%3 == 0 { out += "Fizz" }
- If divisible by 5, add
"Buzz"
to the string:if i%5 == 0 { out += "Buzz" }
- If neither, convert the number to a string and then add it to the output string:
if out == "" { out = strconv.Itoa(i) }
- Print the output variable:
fmt.Println(out)
...