Boolean operators give
even more versatility to programs, think of them as add ons to conditional
statements. With boolean operators instead of having only general conditions
you can have specific conditions. The first boolean is the AND operator and is
denoted with two ampersand symbols like this &&. Here is an example.
Say we had just one variable named age and the conditions determined whether or
not you were a teenager, here's how it looks.
if (age > 12 && age < 20)
{
cout<<"You are a teenager"<<endl;
}
This
condition basically says if age is greater than 12 AND less than 20 then print
out that that person is a teenager since the only ages in between 12 and 20 are
teens. The AND operators requires that both conditions be true in order for the
conditions to execute. If age happened to be 21 it would be greater than 12 but
not less than 20 so the condition would not execute.
The
next boolean operator is OR which is denoted with ||, unlike the AND operator
there will be situation in where you only need one condition to be true in
order for the if condition to execute. OR only requires that one of the
conditions be true, a good example would be in game of craps. In the game of
craps if you roll a 7 or 11 on the first roll then you automatically win, but
if you roll a 2,3, or 12 you automatically lose, sound like a program? Here is
how this can be written.
if (roll==7 || roll==11) //if roll equals 7 OR 11
{
cout<<"You win!"<//if roll equals 2 OR 3 Or 12
}
else{
cout<<"You lose!"<<endl;
}
The
OR operator works like a charm in this situation, also notice how with boolean
operators you aren't restricted with only two conditions, because of this we
are able to come up with much more complex and therefore more versatile
programs.
The
last boolean is what's called the NOT and is notated with an exclamation mark.
NOT is very straightforward the condtion will return opposite of what it was.
For instance, if the condition was true it would return false and not execute
and if the condition was false it would be returned true and execute, here is
an example.
if !(4 < 12)
Normally
this condition obviously wouldn't execute but because of the NOT operator it
would. Here is a recap on boolean operators.
AND && //both condition must be true
OR || //only one condition must be true
NOT ! //returns the opposite
0 comments:
Post a Comment