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

Brian Uribe
Brian Uribe
3,488 Points

I'm not understanding the answer

So I found the answer by googling the question, but i'm not sure how this answer is working. Can someone spell it out? how are &s used? Does it just give me the remainder? I'm so confused.

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


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

1 Answer

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

n is temporary variable and contains an integer (a plain number) which represents each cycle in 1 to 100. 1, 2, 3, 4... And so on until it hits 100.

% or modulo does some math for you and returns remainder. Example: 10 % 2 = 0 because you don't have anything left when dividing 10 with 2. But if you have 11 % 2 you get remainder of 1. Get it? This is useful when you need to identify odd and even numbers. Even number divided with 2 always returns a remainder of 0. If you want to identify an odd number you simply put != that means NOT EQUAL to something.

first line of code: n % 7 == 0 means, n (for example in first cycle it is 1) in this case 1 % 7 EQUALS to 0 AND n, again 1 % 2 IS NOT EQUAL to 0

second line of code: put that n number in our array (1 wouldn't be appended in array because 1 % 7 returns 1, try it in playground. If you try to put 7 % 7 in your playground it will return a 0, and this is our candidate for appending in array)

&& simply means and. When you use it that means that first condition must be met AND second also, you can put more that two && when forming an if statement, just so you know for future.

If these conditions are not met then nothing is appened in our array. When code does 100 cycles it appends only numbers which meet these conditions.