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

I am not able to use the right method for same. I am understanding the concept but really having issues coding it.

var results: [Int] = []

for n in 1...100 { if (n!=0) && (n%7==0) { results.append(n) } }

var results: [Int] = []

for n in 1...100 {
    if (n!=0) && (n%7==0)  {

1 Answer

Jason Anders
Jason Anders
Treehouse Moderator 145,088 Points

Hi Harshit Dixit

You are on the right track, and the conditional has the correct syntax. You are, however, not checking the conditions the instructions are asking for. You have the second part correct to see if it is a multiple of 7, but the first part is only checking if n doesn't equal zero... but the instructions are asking you to check to see if n is an odd number, so there is a vital piece of logic missing. To check if a number is odd, the modulo cannot be zero when divided by 2 (here's where you'd use the not equal to operator. So, it would look something like:

n % 2 != 0

Once you fix that up, the rest is good to go.

Also, a quick note/tip. Watch your spacing in code. While whitespace doesn't really matter with swift, for readability it is best practice to use spacing between characters in code. So instead of:

n%2!=0 //which is very hard to read


n % 2 != 0 //which is very easy to read

Otherwise, nice work! :)