Suppose, in a grandfather clock, we want to implement a chime for all hours except the 00:00 hrs and 12:00 hrs, for which there is a long ring.
Normally, we would check for each hourly time that is not a 12-hourly event, and for each comparison we would do the necessary sound effects. Or, if we are smart, combine all such comparison expressions with the logical OR operator (“||”) and do the check in just a single “if clause.” The pseudo-code would look something like this:
if (time == “01:00hrs” || time==”02:00hrs” || … || time ==”23:00hrs){
trace(“C*HIME” + time);
}else{
trace(“Long-Ring” + time);
}
Clearly, this approach will not serve us well, since we would have to connect together 22
ED: Commonly, spell out numbers under ten only.
expressions in one conditional using OR operators.
Recall that any conditional evaluates to a Boolean value. If the condition evaluates to true, then its COMPLEMENT evaluates to false, and vice-versa. What we need is a new operator: the NOT operator which is simply an exclamation point: !In the above example, if we want to check that the time is NOT '00:00', you'd simple write: if (!(time == “00:00”)) … See how easy that is?
With a little thought, we can do the entire problem that way. Restructuring the above pseudo-code, we can write the following logical equivalent:
if (! (time == “00:00hrs” || time == “12:00hrs)) { //if time is NOT 00:00 or 12:00
trace(“Chime” + time);
}else {
trace(“Long-Ring” + time);
}
Of course, the above code could be rearranged (mainly, the order of the if-else clauses) as:
if (time == “00:00hrs” || time == “12:00hrs”){
trace(“Long-Ring” + time);
}else {
trace(“Chime” + time);
}
Notice that when we turned a negative check to a positive check, the bodies of the if and else blocks were exchanged…the call to chime() went to the new else-clause, and the call to long-ring() went to the new if-clause. That is how Boolean logic works!
Have a question but don't want to ask it publicly? If you are a prime member just ask right here and we will get back to you within 48 hours. Not prime yet? no worries you can ask publicly below.