You can use variables of type boolean like you used the other types we've seen before. If you are getting the input you must keep in mind that typing anything other than true or false will crash your program (that's why many languages don't allow you to read values into boolean variables).
Here is an example program that uses boolean variables (although not for any useful purpose yet):
|
You are a student: true You are a voter: false |
Comparison Operator | Meaning |
is equal to | |
is not equal to | |
is less than | |
is less than or equal to | |
is greater than | |
is greater than or equal to |
The operators >= and <= must be written in that order (ie. => and =< are illegal) and there cannot be any spaces between the two characters. You can write not= with a space between the not and the =. If you reverse the order you will not generate a syntax error, but you will not get the results you expect (8 = not 10 gives false. This is because not 10 = 4294967285. This has to do with the way numbers are stored in the computer using the binary system. We don't want to get into the details here but suffice it to say that x = not y will almost always be false).
Here are some examples of comparisons:
Statement | Result |
10 < 15 | true |
-3.4 >= -2.3 | false |
"one" = "ONE" | false |
5 + 3 > 2 * (20 - 18) | true |
-5 <= -5 | true |
4.6 > 5 | false |
11 not= 11 | false |
You can compare int and real types to each other but otherwise only compare two
values of the same type. In other words don't compare strings with numbers.
When you compare strings lower case letters and upper case letters are not considered
the same (as seen in the previous example). Upper case letters are considered to come before lower case letters (eg. "A" < "a" - we'll
see more detail about this later). Boolean values can only be compared using =
and not=.
|