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 2.0 Collections and Control Flow Control Flow With Conditional Statements Working with Logical Operators

Ivan Cadena
Ivan Cadena
2,949 Points

If statements and logical operators

I have been trying to solve this code challenge and I have not been able to solve it. I had to google how to find the odd numbers and the multiples of 7. Still don't quite understand , can someone please explain?

logicalOperators.swift
var results: [Int] = []

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

3 Answers

Anjali Pasupathy
Anjali Pasupathy
28,883 Points

You only have a couple of things wrong with your code.

Firstly, you need to check to make sure n is odd, not even. This means you need to check to see if n % 2 == 1, not 0

n % 2 == 1 // CHECKS TO SEE IF n IS ODD

Secondly, your if statement isn't structured correctly. This is the basic structure of an if statement:

if /*CONDITION - TYPE BOOL*/ {
    //DO STUFF
}

In this challenge, the CONDITION is checking to make sure n is odd AND divisible by 7. Inside the body of the if statement (the place where you DO STUFF), you append n to the results array.

if n % 2 == 1 && n % 7 == 0 {
    results.append(n)
}

I hope this helps!

Ivan Cadena
Ivan Cadena
2,949 Points

Thank you ! This helps out a lot :)

Yashim Greene
Yashim Greene
866 Points

I have tried this code and it does not work for me. What am I missing?

Anjali Pasupathy
Anjali Pasupathy
28,883 Points

I'm sorry, Yashim. I had an error in my code: instead of "n & 7", I should have written "n % 7". I corrected the error in the code above. Try putting that in your for loop.

Tyron Spencer
Tyron Spencer
1,489 Points

Thankyou Anjali Pasupathy This helped me heaps too :)

Tyron Spencer
Tyron Spencer
1,489 Points

Sorry this might sound silly but im still very new.. What does the & symbol mean (between n&7) I know what the && means, just a bit confused Thankyou :)

Anjali Pasupathy
Anjali Pasupathy
28,883 Points

Actually, that was an error in my code. That should be "n%7", not "n&7". I've corrected it in my solution above. Thanks for pointing this out! (: