TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

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.

   

Hacking with Swift is sponsored by RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

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.