Вы находитесь на странице: 1из 48

C Programming

Class 10
Selection –
Making Decisions
Relational, Equality, and Logical
Operators

Relational less than <


Operators greater than >
less than or equal to <=
greater than or equal to >=

Equality equal to ==
Operators not equal to !=

Logical (unary) negation !


Operators logical and &&
logical or ||
Relational, Equality, and Logical
Operators
Relational less than <
Operators greater than >
less than or equal to <=
greater than or equal to >=
Equality equal to ==
Operators not equal to !=
Logical (unary) negation !
Operators logical and &&
logical or ||
The ! operator is unary. All the other relational,
equality and logical operators are binary. They
all operate on expressions and yield either the int
value 0 or the int value 1.
Representing True or False in C
 Inthe C language, false is
represented by any zero
value.
• False can be represented by an
int expression having a value of
0, a floating value having a
value of 0.0, the null character
‘\0’, or the null pointer.
 Trueis represented by any
nonzero value.
Example of a Relational Operator
 a < b
• is a relational expression
 If a is less than b, the
expression has the value 1
• We consider the expression as
being true
 If a is not less than b, the
expression has the value 0
• We consider the expression as
being false
Common Errors Using
Relational Operators
a =< b /* out of order */
• a <= b /* correct */

a < = b /* no space allowed


between < and = */
• a <= b /* correct */
Values of Relational Expressions
a - b a < b a > b a <= b a >= b

positive 0 1 0 1

zero 0 0 1 1

negative 1 0 1 0

If a - b is positive, that means that a is greater than b.


example: if a is 5 and b is 1.
If a - b is zero, that means a is equal to b.
example: if a is 5 and b is 5.
If a - b is negative, that means a is less than b.
example: if a is 1 and b is 5.
Precedence and Associativity
with Relational Expressions
Declarations and initializations
int i = 1, j = 2, k = 3;
double x = 5.5, y = 7.7;
Expression Equivalent Expression Value

i < j - k i < (j -k) 0

-i + 5 * j >= k + 1 ((-i) + (5 * j)) >= (k + 1) 1

x - y <= j - k - 1 (x - y) <= ((j - k) - 1) 1

x + k + 7 < y / k ((x + k) + 7) < (y / k) 0


Equality Operators & Expressions
 Theequality operators == and
!= are binary operators that
act on expressions.
Values of Equality Expressions
a - b a == b a != b
zero 1 0
nonzero 0 1
Precedence and Associativity
with Equality Operators
Declarations and initializations
int i = 1, j = 2, k = 3;

Equivalent
Expression Expression Value

i == j j == i 0

i != j j != i 1

i + j + k == -2 * -k ((i + j) + k) == ((-2) * (-k)) 1

((1 + 2) + 3) == ((-2) * (-3))


6 == 6
Logical Operators & Expressions
 Thelogical operator ! is
unary, and the logical
operators && and || are
binary.
• When applied to expressions,
each yields either the value 0
or the value 1.
Values of Negation Expressions

a !a

zero 1

nonzero 0
Evaluating Expressions
with Logical Negation
Declarations and Initializations
int i = 7, j = 7;
double x = 0.0, y = 999.9;

Expression Equivalent Expression Value

!(i - j) + 1 (!(i - j)) + 1 2

! i - j + 1 ((!i) - j) + 1 -6

! ! (x + 3.3) ! (! (x + 3.3)) 1

! x * ! ! y (! x) * (!(!y)) 1
Values of Logical Expressions
a b a && b a || b

zero zero 0 0

zero nonzero 0 1

nonzero nonzero 1 1
Truth Table for && and ||
a b a && b a || b

F F F F

F T F T

T F F T

T T T T
Precedence and Associativity of
&& and ||
 Theprecedence of && is
higher than ||, but both
operators are of lower
precedence than all unary,
arithmetic, and relational
operators.
Evaluating Expressions with
Logical && and || Operators
Declarations and Initializations

int i = 3, j = 3, k = 3;
double x = 0.0, y = 2.3;

Expression Equivalent Expression Value

i && j && k (i && j) && k 1

x || i && j - 3 x || (i && (j - 3)) 0

i < j && x < y (i < j) && (x < y) 0

i < j || x < y (i < j) || (x < y) 1


Short Circuit Evaluation
 Withexpressions that contain
the operands && and ||, the
evaluation process stops as
soon as the outcome true or
false is known.
• Given the logical expression
expr1 && expr2
• The evaluation stops if expr1 is
determined to be zero (expr2
will not be evaluated).
Illustration of
Short-Circuit Evaluation
int i, j;
i = 2 && (j = 2); /* what is printed */
printf(“%d %d\n”, i, j); /* 1 2 */

(i = 0) && (j = 3);
printf(“%d %d\n”, i, j); /* 0 2 */

i = 0 || (j = 4);
printf(“%d %d\n”, i, j); /* 1 4 */

(i = 2) || (j = 5);
printf(“%d %d\n”, i, j); /* 2 4 */
Example of the Use of
Short-Circuit Evaluation

if (x >= 0.0 && sqrt(x) <= 7.7) {


..... /* do something */

If the value of x is negative,


the square root of x will not be
taken.
The if and if-else Statements
 General Form of if statement.
if (expr)
statement
 If expr is nonzero (true), then
statement is executed.
 Otherwise statement is skipped and
control passes to the next
statement in the program.
Example of an if Statement
if (grade >= 90)
printf(“Congratulations!\n”);
printf(“Your grade is %d.\n”,
grade);

/* The congratulatory statement */


/* is printed only if a grade of */
/* 90 or higher is earned. */
Grouping Statements
Under a Single if
 Two if statements
if (j < k)
min = j;
if (j < k)
printf(“j is smaller than k\n”);
 A more efficient grouping
if (j < k) {
min = j;
printf(“j is smaller than k\n”);
}
The if-else Statement
 GeneralForm of if-else
statement.
if (expr)
statement1
else
statement2
 If expr is nonzero, then
statement1 is executed and
statement2 is skipped.
 If expr is zero, then statement1
is skipped and statement2 is
executed.
Example of if-else Statement
if (x < y)
min = x;
else
min = y;
printf(“Min value = %d\n”, min);

/* Either x or y, whichever has */


/* the lesser value, has its */
/* value assigned to min. */
Embedding if Statements
 Thestatement in an if
statement can also be an if
statement.

if (a == 1)
if (b == 2)
printf(“***\n”);
The “Dangling else”
Semantic Problem
if (grade >= 80)
if (grade < 90)
printf(“Grade = B.\n”);
else /* Wrong */
printf(“Grade = A.\n”); /*Indenting*/
=========================================
if (grade >= 80)
if (grade < 90)
printf(“Grade = B.\n”);
else /* Correct */
printf(“Grade = A.\n”); /*Indenting*/
Solution to the “Dangling else”
 An else attaches to the
nearest if without an else.
 That’s why
if (grade >= 80)
if (grade < 90)
printf(“Grade = B.\n”);
else
printf(“Grade = A.\n”);
is the correct formatting.
/* Find the minimum of three values. */
#include <stdio.h>
int main(void)
{
int x, y, z, min;
printf(“Input three integers: “);
scanf(“%d%d%d”, &x, &y, &z);
if (x < y)
min = x;
else
min = y;
if (z < min)
min = z;
printf(“The minimum value is %d\n”, min);
return 0;
}
Nested Flow of Control
 Flow-of-control statements
such as if can be nested.
 A common nested flow-of-
control construct makes
repeated use of if-else
statements.
Nested if-else Statements
Could be Written Like This:
if (expr1) Except for next statement
statement1 this is a single if-else statement.
else The else with the default statement
if (expr2) is optional. The problem here is
statement2 that the nested else-if statements
else
march off the right side of the
if (expr3)
statement3 screen (or paper).
else
if (expr4)
statement4
else
default statement
next statement
Alternate Style
for else-if Statements
if (expr1) This is the style you will
statement1 see used and it is what
else if (expr2)
you should use.
statement2
else if (expr3)
statement3
else if (expr4)
statement4
else
default statement
next statement
A Ternary Operator
 Theoperators you have
studied so far have been
either unary or binary
operators.
Unary Examples Binary Examples
-x a + b
!y j && k
 Theconditional operator is a
ternary operator.
The Conditional Operator
 General Form
expr1 ? expr2 : expr3
• First, expr1 is evaluated. If expr1
is nonzero (true), then expr2 is
evaluated, and that is the value of
the conditional expression as a
whole.
• If expr1 is zero (false), then expr3
is evaluated, and that is the value
of the conditional expression as a
whole.
Equivalent Code Using if-else
or a Conditional Expression
if (y < z)
x = y;
else
x = z;
x = (y < z) ? y : z;

The () are not necessary since the


precedence of ?: is just above
the assignment operators (and ?:
associates from right to left).
Switch Statements

Comparing Exact Values


The Switch Statement
• The switch statement
provides another way to
decide which statement to switch ( expression ){
execute next case value1 :
statement-list1
• The switch statement case value2 :
evaluates an expression, statement-list2
then attempts to match the case value3 :
result to one of several statement-list3
possible cases case ...
• The match must be an exact }
match.

37
The Switch Statement
• Each case
contains a value switch ( expression ){
and a list of case value1 :
statements statement-list1
case value2 :
• The flow of control statement-list2
case value3 :
transfers to statement-list3
statement case ...
associated with
the first case value }
that matches
38
Switch - syntax
• The general syntax of a switch statement is:
switch
switch ( expression ){
and
case value1 :
case
statement-list1
are
case value2 :
reserved
statement-list2
words
case value3 :
statement-list3
case ...
If expression
} matches value3,
control jumps
to here
The Switch Statement
• The break statement can
switch ( expression ){
be used as the last
case value1 :
statement in each case's statement-list1
statement list break;
case value2 :
• A break statement statement-list2
causes control to transfer break;
to the end of the switch case value3 :
statement statement-list3
break;
• If a break statement is case ...
not used, the flow of
control will continue into }
the next case
Switch Example
• Examples of the switch statement:
switch (option){
case 'A':
aCount++;
break;
case 'B':
bCount++;
break;
case 'C':
cCount++;
break;
}
Switch – no breaks!!!
• Another Example:
switch (option){
case 'A': switch (option){
aCount++; case 'A':
break; aCount++;
case 'B': case 'B':
bCount++; bCount++;
break; case 'C':
case 'C': cCount++;
cCount++; }
break;
}
Switch - default
• A switch statement can have an optional
default case
• The default case has no associated value and
simply uses the reserved word default

• If the default case is present, control will transfer


to it if no other case value matches
• If there is no default case, and no other value
matches, control falls through to the statement
after the switch
The switch Statement

• Switch switch (option){


with case 'A':
aCount++;
default break;
case: case 'B':
bCount++;
break;
case 'C':
cCount++;
break;
default:
otherCount++;
break;
}
Another Example
The following example program performs a specific
arithmetic operation on two numbers within a switch clause :
To Switch or not to Switch
• The expression of a switch statement must result in an
integral type, meaning an integer (byte, short, int,
long) or a char
• It cannot be a boolean value or a floating point value
(float or double)
• The implicit boolean condition in a switch statement is
equality
• You cannot perform relational checks with a switch
statement
END

Вам также может понравиться