Loops - My Solution

#1

Here is how I solved the challenge.

import Cocoa

var i = 0

while i < 5 {

var count = 0

for c in 0...49 {
count += 2
print(count)

}
i += 1
}

#2

The inner loop is repeated 5 times, and each time it does exactly the same thing. What did the book ask you to do?

#3

Here was the challenge from the book.

Use a loop to count by 2 from 0 up to 100. Use another loop to make sure the first loop is run 5 times. Hint: one good way to do this is to use a nested loop.

Mathias, Matthew; Gallagher,John. Swift Programming: The Big Nerd Ranch Guide (Big Nerd Ranch Guides) (p. 56). Big Nerd Ranch Guides. Kindle Edition.

#4

Thank you for that.

Here is another version, which also satisfies the requirement.

var count = 0

// loop five times
for i in 0..<5 {
    // loop 10 times
    for c in 0..<10 {
        print (count)
        count += 2
    }
}
// print the last count
print (count)

But notice how the value of the count variable is now observable from outside the loops.

#5

Yeah, your solution is definitely a better interpretation of the challenge. I tried it again borrowing your inner loop and using a repeat-while loop on the outside and here is what I came up with. I was trying to keep the counting contained in the inner loop, but I didn’t figure it out.

var myCount = 0
print(myCount)
var sum = myCount + 2
var i = 0
repeat {
// loop 10 times
for c in 0…<10 {
print (sum)
sum += 2
}
i += 1
} while i < 5

Thanks for sharing.

#6

if you wanna get rid of compiler warnings and give a little bit of more readability:

var count = 0
// loop five times
for _ in 1...5 {
// loop 10 times
for _ in 1...10 {
    print (count)
    count += 2
}
}
// print the last count
print (count)
#7

I think you have a problem with the question .

Solution :

var count = 0
while count < 5 {
for case let i in 0…100 {
if i % 2 == 0 {
print(i)
}
}
count += 1
}