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

I am literally stuck and cannot even think of what I am supposed to write. HELP??

I have watched the all of the content leading up to this point and have a basic understanding of it so far. But for this challenge I cannot, whatsoever think of what I am supposed to write. I have watched the 2 videos prior to this challenge about 4 times and have a decent understanding of it. Again for this challenge, I cannot move forward and was wondering I could have someone give me somewhat of a walkthrough.

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

for n in 1...100 {
    // Enter your code below
    NO IDEA WHAT TO WRITE
    // End code 
}

1 Answer

andren
andren
28,558 Points

Sure I can provide a step by step walkthrough.

The first thing you have to do in this task is figure out if the number in n is odd. In an earlier lecture you were shown that you can use the % remainder (modulus) operator to figure out if something is even.

if you divide a number by 2 and it has a remainder of 0 then it is even. If you use the != (not equal) operator like this n % 2 != 0 you will check if a number is not even. If a number is not even then it must be odd.

The second thing you need to do is check that n is a multiple of 7. This can also be accomplished using the remainder operator. If the remainder of n and 7 is 0 then n has to be a multiple of seven.

So the first line of loop should look like this:

var results: [Int] = []

for n in 1...100 {
    if n % 2 != 0 && n % 7 == 0 { // Checks if n is both an odd number and a multiple of seven
    }
}

All that is left to do after that is to append n to the results array. That can be done pretty simply by using the append method. I'll illustrate below:

var results: [Int] = []

for n in 1...100 {
    if n % 2 != 0 && n % 7 == 0 { // Checks if n is both an odd number and a multiple of seven
        results.append(n) // Append n to the results array
    }
}

And that is actually all you have to do, the above code will add odd numbers that are multiples of seven to the results array.