GO FURTHER, FASTER: Try the Swift Career Accelerator today! >>

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)

3      

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

3      

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

3      

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 and A/B test your entire paywall UI without any code changes or app updates.

Learn more here

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

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.