Task:
Write a program that prints the numbers from 1 to 100. But for multiples of three print "Fizz" instead of the number and for the multiples of five print "Buzz". For numbers which are multiples of both three and five print "FizzBuzz".
Solutions
Zero case - wrong solution (for better understanding)
In this case you never see "FizzBuzz" in output console, because all items that can be divided by 3 and 5 would be already count with print "Fizz".
// zero - wrong solution
for var i in 1..<101 {
if i % 3 == 0 {
print("Fizz")
} else if i % 5 == 0 {
print("Buzz")
} else if i % 3 == 0 && i % 5 == 0 {
print("FizzBuzz")
} else {
print(i)
}
}
First - simple and easy
// first - for loop
for var i in 1..<101 {
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)
}
}
Second - using magic number 15 because 3 * 5 = 15
//second - foor loop and magic number 15 = 5 * 3
for var i in 1..<101 {
if (i % 15 == 0) {
print("FizzBuzz")
} else if i % 3 == 0 {
print("Fizz")
} else if i % 5 == 0 {
print("Buzz")
} else {
print(i)
}
}
Third - using case instead of if..else statements
// third - for loop and case operator instead of switch
for var i in 1..<101 {
switch i {
case _ where i % 15 == 0:
print("FizzBuzz")
case _ where i % 3 == 0:
print("Fizz")
case _ where i % 5 == 0:
print("Buzz")
default:
print(i)
}
}
Fourth - make result string
//fourth - make a result string
for var i in 1..<101 {
var str = ""
if i % 3 == 0 {
str = str + "Fizz"
}
if i % 5 == 0 {
str = str + "Buzz"
}
if str == "" {
str = String(i)
}
print(str)
}
You have shared a very informative Article. I was looking for this kind of unique information. Please share more related information so I can get more knowledge.
ReplyDelete-Custom Web Design and Development
A big shout out to you, such a useful and thought provoking article on Custom WebsiteA straight from an intellectual mind
ReplyDeleteThank you for writing this blog and giving this vital and useful information. Best Custom Websites
ReplyDeleteThank you very much for drawing my notice to this. Your blog is jam-packed with useful facts. Until I read that, I would have no idea. I'll come back for more fantastic material.
ReplyDeleteBest wishes, and good luck.
Web Design USA
Good content. I was looking for this type of content. Saved my time for further search.
ReplyDeleteYou should always provide that type of content. I appreciate your determination to give the students a good title.Custom Designed Websites
Great share!One of the best blogs I have Ever Seen. Keep going!
ReplyDeleteQA Testing Services
Excellent website. This is the first time I've visited this blog, and it's fantastic. The main thing is that the content in this blog is written in a clear and intelligible manner.
ReplyDeleteSEO Agency