Section 9.3 Relational and Equality Operators
We have already learned about several operators for numbers:
+, -, * addition, subtraction, and multiplication (integers and floats)
/ integer division for integers and floating point division for floats
% remainder (modulus) of an integer division
Next, weβll learn about relational and equality operators that serve to compare the values of two quantities:
<, > less than and greater than operators
<=, >= less than or equal to, greater than or equal to
!= not equal to
== equal to (note the double equal sign; the single equal sign = has already been βused upβ for our assignment operator)
Investigate 9.1 .
Which of the following variables would C interpret as "true"? For example, if each variable was placed in the following codeβs
if statement as "variable", would the program output "True" or "False"?
int a = -1
char b = 'b'
float c = 0.0
int d = 4000
if (variable){
printf("True")
}
else{
printf("False")
}
A true logical relation evaluates to 1, whereas a false relation evaluates to 0. Examples:
Suppose x has the value 3.5. Then (x <= 5.0) evaluates to 1.
Suppose next that x has the value 7. Then (x <= 5.0) evaluates to 0.
(age == 30) evaluates to 1 if indeed age has the value 30, otherwise it evaluates to 0.
Note: Instead of
(x <= 5.0) you could also write
(5.0 >= x), and instead of
(age == 30) you could just as well write
(30 == age).
Investigate 9.2 .
Does the following statement, which is comparing two characters, evaluate to
true or
false , according to C?
('A' > 'a')
Letβs look at an example.
If you cannot see this codecast, please click here .
Aside: Video Description.
Logic expressions resulting from comparing variable values
Producing true/false relations
Using if-else based on true/false values of logic statements
Example: an if statement can include a logic statement such as (x>5), and it will then execute code if this logic statement evaluates to true