Implement Fizz-Buzz Fast AF
Fizz Buzz is a simple coding challenge often used as a way to introduce programming concepts to beginners. It involves printing out the numbers 1 to 100, with the following rules:
- If the number is divisible by 3, print “Fizz” instead of the number
- If the number is divisible by 5, print “Buzz” instead of the number
- If the number is divisible by both 3 and 5, print “FizzBuzz” instead of the number
In this tutorial, we will go through the steps of implementing Fizz Buzz in Swift.
Step 1: Set up a for loop to iterate through the numbers 1 to 100.
for i in 1...100 {
}
Step 2: Use an if statement to check if the number is divisible by both 3 and 5. If it is, print “FizzBuzz”.
if i % 3 == 0 && i % 5 == 0 {
print("FizzBuzz")
}
Step 3: If the number is not divisible by both 3 and 5, use another if statement to check if it is divisible by 3. If it is, print “Fizz”.
else if i % 3 == 0 {
print("Fizz")
}
Step 4: If the number is not divisible by either 3 or 5, use another if statement to check if it is divisible by 5. If it is, print “Buzz”.
else if i % 5 == 0 {
print("Buzz")
}
Step 5: If the number is not divisible by either 3 or 5, print the number.
else {
print(i)
}
Here is the complete code for Fizz Buzz in Swift:
for i in 1...100 {
if i % 3 == 0 && i % 5 == 0 {
print("FizzBuzz")
}
else if i % 3 == 0 {
print("Fizz")
}
else if i % 5 == 0 {
print("Buzz")
}
else {
print(i)
}
}
Why might you use Fizz Buzz? It’s a great way to introduce programming concepts such as loops, conditionals, and modulo operator to beginners. It’s also a common question in programming interviews, as it tests a candidate’s ability to think logically and write clean code.
In conclusion, Fizz Buzz is a simple coding challenge that can be implemented in Swift using for loops and if statements. It’s a useful tool for introducing programming concepts to beginners and testing a candidate’s logical thinking skills in an interview setting.