WWDC24 SALE: Save 50% on all my Swift books and bundles! >>

SOLVED: Checkpoint 3 Nested loop efficiency question

Forums > 100 Days of SwiftUI

Hi all, Just started this course and on Day 6 now. I had a question regarding the FizzBuzz checkpoint. I know I can solve it with a if/else if/else if/else condition, specifically by checking the && condition in the first if statement, but is the below approach not prefered for any reason? Is it less efficient to have a while loop in there to check for the && multiple condition and then break out of the loop?

Note: super beginner and just trying to understand if both approaches are a matter of preference or is one just not recommended as its not as efficient and bad practice

for i in 1...100{
    while i % 3 == 0 && i % 5 == 00{
        print ("\(i) FizzBuzz")
        break 
    }
    if i % 3 == 0 {
        print("\(i) Fizz")
    } else if i % 5 == 0{
        print("\(i) Buzz")
    } else {
        print("\(i) ...")
        }
} 

   

I don't know about efficiency, but semantically it doesn't make much sense to do it that way.

You are checking one number (whatever the current value of i is), why would you use a loop to do so?

   

@roosterboy. I suspect you have not watched the checkpoint 3 video? The very first part says "Your goal is to loop from 1 to 100". That would be a good reason for OP to use a loop in his logic?

   

The for loop, yes. That is going over the numbers from 1 to 100.

But not the inner while loop. That is looping over the value of i each time through the for loop, so it's "looping" over... 1 number.

   

Oh I see My appologies, thought you were talking about the for loop. I was like, I hope not lol otherwise I got it wrong too. Yeah I agree the while loop is redundant.

   

Yeah makes sense. Thanks guys. I guess I was caught up in the simple solution being 'too simple' but it seems to be the right thing to do.

   

Save 50% in my WWDC sale.

SAVE 50% To celebrate WWDC24, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.