Logical Relational If
Logical Relational If
Expressions
C Programming
Lecture Topics
• Using Relational and Logical Operators to
Construct and Evaluate Logical
Expressions
• If-Else Statements
Flow of Control
• is Sequential unless a “control structure” is
used to change that
• Repetition
for loop
while loop
do . . . while loop
Control Structures
• C allows a program to make a decision
based on the value of a condition. Such a
condition must evaluate to true or false.
3 Logical Operators
! && ||
6 Relational Operators
are used in expressions of form:
ExpressionA Operator ExpressionB
abs (number ) == 35
initial != ‘Q’
int x, y ;
x = 4;
y = 6;
EXPRESSION VALUE
x<y true
x+2<y false
x != y true
x + 3 >= y true
y == x false
y == x+2 true
Operator Meaning Associativity
! NOT Right
*, / , % Multiplication, Division, Modulus Left
+,- Addition, Subtraction Left
< Less than Left
<= Less than or equal to Left
> Greater than Left
>= Greater than or equal to Left
== Is equal to Left
!= Is not equal to Left
&& AND Left
|| OR Left
= Assignment
LOGICAL
EXPRESSION MEANING DESCRIPTION
p || q p OR q p || q is true if either
p or q or both are true.
It is false otherwise.
What is the value?
age = 25;
height = 70;
EXPRESSION VALUE
false
true
true
Must still be evaluated because truth value
of entire expression is not yet known. Why?
Result of && is only true if both sides are
true.
What happens?
int age, height;
age = 25;
height = 70;
EXPRESSION
! (height > 60) || (age > 50)
true
false
Does this part need to be evaluated?
Write an expression for each
taxRate is over 25% and income is less than 20000
(taxRate > .25) && (income < 20000)
age is 21 or 22
(age == 21) || (age == 22)
Comparing float Values
• do not compare float values for equality,
compare them for near-equality.
float myNumber;
float yourNumber;
…….
• For example:
– -1 is true
– 299 is true
– 0 is false
Equality Vs Assignment
• Given:
if (grade = 100)
printf (“Perfect Score!”);
if ( Expression )
StatementA
else
StatementB
TRUE FALSE
expression
if ( Expression )
{
“if clause”
}
else
{
“else clause”
}
int carDoors, driverAge ;
double premium, monthlyPayment ;
. . .
if ( (carDoors == 4 ) && (driverAge > 24) )
{
premium = 650.00 ;
printf( “ LOW RISK “) ;
}
else
{
premium = 1200.00 ;
printf(“HIGH RISK ”) ;
}
volume = 1;
else
volume = 2;
code = 0;
if ( ! code )
printf( “Yesterday”);
else
printf( “Tomorrow”);
What output? and Why?
int age;
age = 30;
if ( age < 18 )
int age;
age = 20;
if ( age == 16 )
{
printf( “Did you get driver’s license?”) ;
}
If--Else for a mail order