NEW: Subscribe to Hacking with Swift+ and accelerate your learning! >>

SOLVED: confusion with Repeat While loop

Forums > Swift

Hey Guys,

I am having a little difficulty fully understanding the repeat while loop concept. For example, I am trying to find the first 10 factors of 2 from the list of numbers 1 to 100. Easy right? I was able to do this easily with a for loop, which gave me answers [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

var evenNumber = [Int]()
var counter = 10

for num in 1...100 {
    if num % 2 == 0 {
        counter -= 1
        evenNumber.append(num)

        if counter == 0 {
            break
        }
    }
}

print(evenNumber)

However, I can't seem to achieve the same results with the repeat / while loop. The result gave me all 50 of the facotrs of 2 from 1 ... 100 instead of just the first 10 factors. What am I doing wrong?

var evenNumber = [Int]()

repeat {
    for num in 1...100 where num % 2 == 0 {
        evenNumber.append(num)
    }
} while evenNumber.count <= 10

print(evenNumber)

   

hi,

although you have an outer repeat ... while loop, the first time the body of the loop executes, it runs its own loop -- from 1 to 100, appending lots of numbers to your evenNumber array. the outer loop runs exactly once.

what you really are trying to do is something like this:

var evenNumber = [Int]()
var num = 0
repeat {
    num += 1
    if num % 2 == 0 {
        evenNumber.append(num)
    }
} while evenNumber.count < 10 && num < 100 // note check here on the range for num
print(evenNumber)

hope that helps,

DMG

   

@delawaremathguy: THANK YOU DMG!! That REALLY HELPED! I am so happy.

   

Hacking with Swift is sponsored by Paw

SPONSORED Use Paw to build, test and describe web APIs. Paw has a lightning fast native macOS interface to compose requests, collaborate in real-time on API specs, and generate client code for your applications. You can import and export API definitions.

Discover Paw for Mac

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

Not logged in

Log in
 

Link copied to your pasteboard.