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

Emilio Robres
Emilio Robres
2,728 Points

Why my code it is not correct ?

Why it is not correct?

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

for n in 1...100 

    if  (n / 2 != 0) && (n / 7 = 0) {
     results.append (n)
}

1 Answer

Logan R
Logan R
22,989 Points

What's up!

So you have 3 main issues with your code.

The first issue is that you're missing a "}" after your if statement.

The second issue is that the second part of the if statement has a logical error. You are saying "(n / 7 = 0)". If you look carefully, you only have 1 =. This means you are setting "n / 7" equal to 0 instead of checking if it is equal to zero.

The last issue is your biggest issue. You are using the wrong operator. Let's take a look at the even or odd part. Your statement says "n / 2". Does this do what you think it does? It is suppose to report 0 if the number is even and 1 if the number is odd.

>>> 1 / 2
0
>>> 2 / 2
1
>>> 3 / 2
1
>>> 4 / 2
2
>>> 5 / 2
2
>>> 6 / 2
3

You do not want to divide the number. This gives you how many times n goes into 2. You instead want to get the remainder of n. That is, what is left over when you can no longer subtract 2 from n. We use the modulo operator ("%") to do this.

>>> 1 % 2
1
>>> 2 % 2
0
>>> 3 % 2
1
>>> 4 % 2
0
>>> 5 % 2
1
>>> 6 % 2
0

Does this make sense? When we look at the second part "is the number divisible by 7?", this is asking the same as above. The difference is that instead of "Is the number divisible by 2?", it's 7.

Here is an example where we test if n is divisible by 4:

>>> 1 % 4
1
>>> 2 % 4
2
>>> 3 % 4
3
>>> 4 % 4
0
>>> 5 % 4
1
>>> 6 % 4
2
>>> 7 % 4
3
>>> 8 % 4
0

Hopefully this helps clear up your question! If not, please add a comment and I'll try to better explain or someone else may be able to explain it better.