Selection Structures:
if and switch Statements
Objectives
‣ to become familiar with three kinds of control
structures: sequence, selection and repetition
‣ to understand compound statements
‣ to learn how to compare numbers and characters
‣ to learn how to use the relational, equality and logical
operators to write expressions that are true or false
‣ to learn how to implement decisions in algorithms
using control structures
2
Control Structures
‣ control the flow of execution in a program or function
‣ enable you to combine individual instructions into a single
logical unit with one entry point and one exit point
‣ the order of statement execution is called the flow of control
3 Kinds of Control Structures
1. Sequence
2. Selection
3. Repetition
3
Control Structures
Compound Statement
‣ group of statements bracketed by { and } is used to specify
sequential flow
statement1;
statement2;
statementn;
4
Some problem solutions require steps with two or more
alternative courses of action. A selection control structure
chooses which alternative to execute.
5
Conditions
‣ expressions that establish a criterion for either
executing or skipping a group of statements
‣ expressions that are either false (represented by 0)
or true(usually represented by 1)
‣ often uses one or a combination of C’s equality
operators, relational operators and logical
operators which all return Boolean results
6
Relational and Equality Operators
Most conditions that we use to perform comparisons
will have one of these forms:
7
Relational and Equality Operators
8
Relational and Equality Operators
Here are some sample conditions in C. Each condition is
evaluated assuming these variable and constant macro values:
9
Logical Operators
‣ expressions that uses one or more of the logical
operators can form complex conditions
‣ all logical operators have lower precedence than
the relational operators
‣ Logical NOT (!) has higher precedence than
Logical AND (&&) and Logical OR (||)
10
Logical Operators
Logical AND ( && )
11
Logical Operators
Logical OR ( || )
12
Logical Operators
Logical NOT ( ! )
13
Logical Operators
salary < MIN_SALARY || dependents > 5
The logical expression above determines whether an employee is eligible
for special scholarship funds. It evaluates to 1 (true) if either the condition
salary < MIN_SALARY
or the condition
dependents > 5
is true.
14
Logical Operators
temperature > 90.0 && humidity > 0.90
The logical expression above describes an unbearable
summer day, with temperature and humidity both in the
nineties. The expression evaluates to true only when
both conditions are true.
15
Operator Precedence
An operator precedence determines it’s order of evaluation
You can use parentheses to change the order of operator evaluation in an
expression
16
Evaluating Expressions
An operator precedence determines it’s order of evaluation
!flag
x + y / z <= 3.5
!flag || (y + z >= x - z)
!(flag || (y + z >= x - z))
17
Evaluating Expressions
An operator precedence determines it’s order of evaluation
!flag !0 is 1 (true)
x + y / z <= 3.5 5.0 <= 3.5 is 0 (false)
!flag || (y + z >= x - z) 1 || 1 is 1 (true)
!(flag || (y + z >= x - z)) !(0 || 1) is 0 (false)
18
Evaluating Expressions
Short-Circuit Evaluation
‣ technique of stopping evaluation of a logical expression as soon as its
value can be determined
19
Writing English Conditions in C
To solve programming problems, you must convert
conditions expressed in English to C
Example:
Given that x=3.0, y=4.0 and z=2.0
20
Writing English Conditions in C
DeMorgan’s Theorem
‣ gives us a way of simplifying logical expressions
It states,
๏ The complement of expr1 && expr2 is written as comp1 || comp2
where comp1 is the complement of expr1, and comp2 is the
complement of expr2
๏ The complement of expr1 || expr2 is written as comp1 && comp2
where comp1 is the complement of expr1, and comp2 is the
complement of expr2
21
Writing English Conditions in C
Example
Using DeMorgan’s theorem, we can write the complement of
(status == ‘S’ || status == ‘D’) && age > 25
as
(status != ‘S’ && status != ‘D’) && age <= 25
The original condition is true for anyone who is over 25 and is either
single or divorced. The complement would be true for anyone who is
25 or younger, or for anyone who is currently married.
22
Writing English Conditions in C
Write an expression to test for each of the following relationships
1. age is from 18 to 21 inclusive
2. water is less than 1.5 and also greater than 0.1
3. year is divisible by 4
4. speed is not greater than 55
5. y is greater than x and less than z
6. w is either equal to 6 or not greater than 3
23
Writing English Conditions in C
Write assignment statements for the following:
1. Assign a value of 0 to between if n is less than -k or
greater than +k; otherwise, assign 1.
2. Assign a value of 1 to divisor if digit is a divisor of
num; otherwise, assign a value of 0.
3. Assign a value of 1 to lowercase if ch is a lowercase
letter, otherwise, assign a value of 0.
24
CONTROL STRUCTURES
Selection Structure
‣ a control structure that chooses among alternative
program statements
if Statement
‣ is the primary selection control structure
‣ is a conditional statement used to check condition
or to control the flow of execution of statements
‣ the execution of a whole program is done in one
direction only
25
CONTROL STRUCTURES
Selection Structure
if Statement (One Alternative)
Syntax: Example:
if(condition) if(score > 110)
{ {
statementT; status = ‘Passed’;
} }
In above syntax, the condition is checked first. If it evaluates to true (nonzero
value) then the program control flow goes inside the braces and executes the
block of statements associated with it. If it returns false, then program skips the
braces. If there are more than one statements in if Statement then use {} braces
else it is not necessary to use.
26
CONTROL STRUCTURES
Selection Structure
if Statement (Two Alternatives)
Syntax: Example:
if(condition) if(score > 110)
{ {
statementT; status = ‘Passed’;
} }
else else
{ {
statementF; status = ‘Failed’;
} }
In above syntax, the condition is checked first. If it evaluates to true (nonzero
value) then the program control flow goes inside the braces and executes
statementT and skips statementF. Otherwise, it skips statementT and
executes statementF
27
CONTROL STRUCTURES
Selection Structure
if Statements having compound statements after the condition
In the syntax below, the condition is checked first. If it is true, then the
program control flow goes inside the braces and executes the block of
statements associated with it.
Syntax: Example:
if(condition) if(x > y)
{ {
temp = x;
statement1; x = y;
statement2; y = temp;
. . . }
statementn;
} 28
CONTROL STRUCTURES
Selection Structure
if Statements having compound statements on both true (after
condition) and false task (after keyword else)
Syntax: Example:
if(condition) if(x > y)
{ {
statement1; x = x + 10.0;
. . . printf(“x is Bigger.\n”);
statementn;
}else{
}else{
printf(“x is Smaller.\n”);
statement1; printf(“y is %2.f .\n”,y);
. . .
statementn; }
}
29
CONTROL STRUCTURES
Selection Structure
Nested if Statements and Multiple Alternative Decisions
Syntax: Example:
if(condition1) if(score > 110 )
{ {
statement1; grade = ‘A’;
} }
else if(condition2) else if(score > 90)
{ {
statement2; grade = ‘B’;
} }
else if(conditionn) else if(score > 70)
{
{
grade = ‘C’;
statementn; }
} else
else {
{ grade = ‘D’;
statemente; }
} 30
CONTROL STRUCTURES
Selection Structure
Nested if Statements with more than one variable
Syntax: Example:
if(conditionfilter)
if(road_status == ‘S’ )
{
{
if(conditiont)
{ if(temp > 0)
statementt; {
} printf(“Wet Road!”);
else }
{ else
statementf; {
} printf(“Icy Road!”);
}
} else
else {
{ printf(“Drive carefully!\n”);
statemente; }
} 31
CONTROL STRUCTURES
Selection Structure
switch Statement
‣ also used in C to select on of several alternatives
‣ especially useful when the selection is based on
the value of a single variable or of a single
expression called the controlling expression whose
value maybe of type int or char but not of type
double.
32
CONTROL STRUCTURES
Selection Structure
switch Statement
Syntax: Example:
switch(expression) switch(watts)
{ {
case expr1:
case 25:
statements;
life = 2500;
break; break;
. . . case 60:
life = 1000;
case exprn: break;
statements;
break; case 100:
life = 750;
break;
default:
statements; default:
life = 0;
} } 33
CONTROL STRUCTURES
Selection Structure
Example
Increase one of three variables (num_pos, num_neg, num_zero) by 1,
depending on whether x is greater than zero, less than zero, or equal to zero,
respectively.
Using nested if,
if (x > 0){
num_pos = num_pos + 1;
}
else {
if (x < 0)
num_neg = num_neg + 1;
else
num_zero = num_zero + 1;
34
CONTROL STRUCTURES
Selection Structure
Example
Increase one of three variables (num_pos, num_neg, num_zero)
by 1, depending on whether x is greater than zero, less than zero,
or equal to zero, respectively.
Using a sequence of ifs,
if (x > 0)
num_pos = num_pos + 1;
if (x < 0)
num_neg = num_neg + 1;
if (x == 0)
num_zero = num_zero + 1;
35
CONTROL STRUCTURES
Selection Structure
Example
Increase one of three variables (num_pos, num_neg,
num_zero) by 1, depending on whether x is greater than
zero, less than zero, or equal to zero, respectively.
Using a multiple-alternative decision form of nested if,
if (x > 0)
num_pos = num_pos + 1;
else if (x < 0)
num_neg = num_neg + 1;
else
num_zero = num_zero + 1;
36
CONTROL STRUCTURES
Selection Structure
Implement the following decision table that categorizes a
systolic blood pressure reading. Assume that the systolic
blood pressure has been input as an integer.
37
CONTROL STRUCTURES
Selection Structure
Write a nested if statement for the decision diagrammed in
the accompanying flowchart. Use a multiple-alternative if
for intermediate decisions where possible.
38
CONTROL STRUCTURES
Selection Structure
What will be printed by this carelessly constructed switch
statement if the value of color is ‘R’?
switch(color){
case ‘R’:
printf(“Red\n”);
case ‘B’:
printf(“Blue\n”);
case ‘Y’:
printf(“Yellow\n”);
}
39
CONTROL STRUCTURES
Selection Structure
Given the following functions what will be the value returned after calling,
fun2(fun1(1,2,3), fun1(4,5,6));
int fun1(int a, int b, int c) int fun2(int a, int b)
{ {
if ((a >= b) && (a >= c)){ if (a < b){
return a; return a;
} }
else if ((b >= a) && (b >= c)){ else{
return b; return b;
} }
else{ }
return c;
}
40
CONTROL STRUCTURES
Selection Structure
Write C statements to carry out the following steps.
1. if item is nonzero, then multiply product by item and
save the result in product; otherwise, skip the
multiplication. In either case, print the value of product.
2. Store the absolute difference of x and y in y, where the
absolute difference is (x-y) or (y-x), whichever is
positive. Do not use the abs or fabs function in your
solution.
3. If x is 0, add 1 to zero_count. If x is negative, add x to
minus_sum. If x is greater than 0, add x to plus_sum.
41