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

How to do this question ?

So I basically have the sense of solving this question , but I just cannot figure out how to do . Can anyone help me pls

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

for n in 1...100 {
    // Enter your code below
    if n/7 || n+=2 {
    result.append[n]
    }
    // End code 
}

The Question: For this challenge, we'd like to know in a range of values from 1 to 100, how many numbers are both odd, and a multiple of 7.

To start us off, I've written a for loop to iterate over the desired range of values and named the local constant n. Your job is to write an if statement inside the for loop to carry out the desired checks.

If the number is both an odd number and a multiple of 7, append the value to the results array provided.

Hint: To check for an odd number use the not operator to check for "not even"

1 Answer

Alex Koumparos
MOD
Alex Koumparos
Python Web Development Treehouse Moderator 33,371 Points

Hi Michael,

You have the right general idea, but you have a couple of errors.

Let's look at a simplified conditional example with a single condition:

if n/7 {
    // do something
}

An if statement has to test a boolean (i.e., true or false). Therefore any expression we use as a conditional must evaluate to true or false. n/7 evaluates to a number, not a boolean. We can fix this by explicitly asking whether the value is equal to some specific value (e.g., zero):

if n/7 == 0 {
    // do something
}

Now this code is valid, but we're actually using the wrong operator to achieve what the challenge is asking. If we want to test whether some number is a perfect multiple of another number, we are testing whether the remainder of dividing the one by the other is equal to zero. Swift gives us an operator for checking the remainder of an integer division: the modulo (%) operator.

Testing whether a number is odd or even is just a special case of checking whether a number is a multiple of another number, in this case 2. Any number that is a multiple of 2 is even, and any number not a multiple of 2 is odd. Thus we can use the same modulo operator to test whether n is even or odd.

Hope that helps,

Cheers

Alex