So yesterday, we looked at if statements and how to use them with simple conditions. To make our conditions more complicated, we need to make use of more of the logical operators. I'll give a real life example:
"It is sunny and I am not indoors."
A pretty simple statement. Not thinking about coding right now, let's let:
p = It is sunny
q = I am indoors
If we wanted to write this as a condition for an if statement, we would have:
p && !q
Pretty simple, right? Now let's look at the statement:
"It is sunny or cloudy, but not raining."
An important note about logic: BUT has the same logical meaning as AND. So we have:
"It is sunny or cloudy, and not raining."
Now, an important point about how this statement is interpreted. Do you remember BEDMAS, the order of operations when doing arithmetic? This states that certain operators must be evaluated before others (the order is: brackets, exponents, division/multiplication, addition/subtraction). Well logical operators also possess a precedence factor as you'll see. Let's look at our statement again. It states that it is sunny or cloudy, but not raining. At first glance, it may seem at though the condition first checks to see whether it is sunny or cloudy, and then checks to see if it is raining. i.e. this:
(sunny or cloudy) and raining
In fact, when dealing with logic, I like to think of AND as a multiplication symbol and OR as addition (there's a discrete mathematical property that actually says this, but I won't get into that). In other words, AND will precede OR when dealing with operations, so our original statement actually means this:
sunny or (cloudy and raining)
See how it completely changes the sense of our condition? It's like comparing:
(5 * 5) + 10 = 250
5 * (5 + 10) = 75
Just a note to be careful when coding.
Great, now that that's out of the way, you are legally entitled to see some code.
Let's say we are writing a program in which we are asking the user for a time in hours and minutes. Obviously, we don't want to deal with hours greater than the number of hours in a day or minutes greater than 60, so a common fix is to set a default value if the user enters invalid data. We'll work from hours 0 to 23
//prompt user for data
if(hour<0 || hour>23)
if(min<1 || min>60)
Notice how we cannot use mathematical notation like: 0<hour<23. Instead, we must explicitly show each condition we want to include.
I hope this has been useful!
Next time, I'll talk about loops.