Transcript LECT14.PPT

Relational Operators
What is TRUE anyway?
CMSC 104
1
Relational Operators
<
>
<=
>=
==
!=
less than
greater than
less than or equal to
greater than or equal to
is equal to
is not equal to
Relational expressions evaluate to the int
value 1 (True) or the int value 0 (False)
CMSC 104
All of these operators are called binary operators
because they take two expressions as operands
2
Practice with Relational Expressions
int a = 1, b = 2, c = 3;
Expression Value Expression Value
a < c
a + b >= c
b <= c
a + b == c
c <= a
a != b
a>b
a + b != c
b >= c
CMSC 104
3
True or False

Arithmetic expressions also evaluate to
true of false.

Any expression that has a zero value is
false.

Any expression that has a non-zero
value is true.
CMSC 104
4
Practice with Arithmetic Expressions
int
a = 1, b = 2, c = 3;
float x = 3.33, y = 6.66;
Expression
Value
True/False
a+b
b-2*a
c-b-a
c-a
y-x
y-2*x
CMSC 104
5
Structured Programming

All programs can be written in terms of
only 3 control structures
o The sequence structure
– Unless otherwise directed, the statements are
executed in the order in which they are written.
o The selection structure
– Used to choose among alternative courses of
action
o The repetitive structure
– Allows that an action is to be repeated while
some condition remains true.
CMSC 104
6
A Selection Structure
the if statement
if ( condition )
{
statement(s)
}
if ( value == 0 )
{
printf (“The value you entered was zero\n”);
}
CMSC 104
7
if - else
if ( condition )
{
statement(s)
}
else
{
statement(s)
}
CMSC 104
/* the if clause */
/* the else clause */
8
Example of if - else
if ( value == 0 )
{
printf (“The value you entered was zero\n”);
}
else
{
printf (“You didn’t enter a zero\n”);
}
CMSC 104
9
if - else if - else
CMSC 104
if (condition)
{
statement(s)
}
else if (condition) /* there may be multiple */
{
/* else if clauses
*/
statement(s)
}
else
{
statement(s)
}
10
Example
CMSC 104
if ( value == 0 )
{
printf (“The value you entered was zero\n”);
}
else if ( value < 0 )
{
printf (“%d is negative.\n”, value);
}
else
{
printf (“%d is positive.\n”, value);
}
11
Gotcha - The common error of using
= when we really want ==
int a = 2;
if (a = 1)
{
printf (“a is one\n”);
}
else if (a == 2)
{
printf (“a is two\n”);
}
else
{
printf (“The value of a is %d\n”, a);
}
CMSC 104
12
Gotcha (continued)



CMSC 104
An assignment expression used as a condition,
as in if (a = 1) is legal so no error message
will be produced.
The assignment expression has a value, the
value being assigned. In this case 1 which is
true. If the value being assigned was 0, then the
expression would evaluate to 0 or false.
This common typo typically causes the program
to do the exact opposite of what we’d like, so if
you get very strange results, look for this
problem.
13