Day 2 on 100 days of code, working on if statements and logical operators.  There are three kinds of logical operators that make writing code more readable. The operators are: && and, || or, ! not.

        A && B      and     both expressions must be true
        A || B      or      only one expression needs to be true
        A != B      not     makes a true expression false vice versa

The code challenge was about thinking of writing a condition that accepted integers if they were both divisible by 7 and an odd number.  The variable was n to keep it simple, when the conditions are met I append the values to an empty array.

var results: [Int] = []
for n in 1100 {
    // both odd and a multiple of 7

It’s one of the exercises that focuses you on thinking how to make a condition true before you think of code. Once you get it then you can use whatever logical operator you want. So if I can divide n and not get a remainder of 0 then it must be an odd number right ?

if n % 2 != 0

This basically says the variable n representing an integer divided by 2 has a remainder not equal to 0.  The % symbol gives the remainder of n and 2, ex. 3 % 9 = 3.  Lastly != 0 means not equal to 0, if n % 2 gives a remainder its an odd number.

With the logic in mind I can write out two conditions side by side and use a logical operator to pass the challenge. I solved it like this.

if (n % 7) == 0 && (n % 2) != 0 {
        print(“I know how to solve this”)

In the body of the if statement I append the n values to the empty results array.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s