NEW: Start my new Ultimate Portfolio App course with a free Hacking with Swift+ trial! >>

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 Fernando Olivares

SPONSORED Would you describe yourself as knowledgeable, but struggling when you have to come up with your own code? Fernando Olivares has a new book containing iOS rules you can immediately apply to your coding habits to see dramatic improvements, while also teaching applied programming fundamentals seen in refactored code from published apps.

Try the book!

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.