Checkpoint 3
03 Mar 2023Description
The problem is called fizz buzz, and has been used in job interviews, university entrance tests, and more for as long as I can remember. Your goal is to loop from 1 through 100, and for each number:
If it’s a multiple of 3, print “Fizz”
If it’s a multiple of 5, print “Buzz”
If it’s a multiple of 3 and 5, print “FizzBuzz”
Otherwise, just print the number.
Code
for num in 1..100 {
var fizz = num % 3 == 0
var buzz = num % 5 == 0
if fizz && buzz {
print("FizzBuzz")
} else if fizz {
print ("Fizz")
} else if buzz {
print ("Buzz")
} else {
print(num)
}
}
Explanation
Here I have the classic fizzbuzz challenge in Swift.
Using a if else tree where the program looks for the most general condition first before looking for the more specific conditions I am able to accuratly print the needed value.