Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS Swift Collections and Control Flow Control Flow With Conditional Statements Working With Logical Operators

How I can add if in loop?? Always a mistake! In what part of loop?

var results: [Int] = []

for n in 1...100 { if <#condition#> { <#code#> } } ERRORE?

2 Answers

Kyle Johnson
Kyle Johnson
33,528 Points

You can always reference the Swift Programming Guide. I found this example there:

for index in 1...5 {
    print("\(index) times 5 is \(index * 5)")

    if (index % 2 == 0) {
        print("\(index) is even")
    }
}
// 1 times 5 is 5
// 2 times 5 is 10
// 3 times 5 is 15
// 4 times 5 is 20
// 5 times 5 is 25
// 2 is even
// 4 is even

WARNING! Solution below! For the challenge, this should help:

var results: [Int] = []

for n in 1...100 {
    // Enter your code below
    if (n % 2 != 0 && n % 7 == 0) {
      results.append(n)
    }
    // End code 
}

But I don't understand without !=0 and ==0 I see an error. For what are these values (!=0 and ==0) ?

Kyle Johnson
Kyle Johnson
33,528 Points

!= means 'not equal' and == means 'equal'

I understand what they mean, I don't understand what for (!=0 and ==0) are in this situation if (n % 2 != 0 && n % 7 == 0)? We have for n in 1...100 = what for (!=0 and ==0) ???

Kyle Johnson
Kyle Johnson
33,528 Points

This formula finds out if their is a remainder after dividing by 2: n % 2 != 0. If their is a remainder, n % 2 will not equal 0. This formula finds out if their is a remainder after dividing by 7: n % 7 == 0. If their is a remainder, n % 7 will not equal 0.

The for loop will iterate through all numbers starting at 1 going to 100. To find the odd number we want to divide the number by 2 and check to see if their is a remainder. If there is a remainder, we have an odd number. Same concept for finding numbers divisible by 7 only this time we want number that give us a remainder of 0.

Ok) thank you so much!

Thank you :)