Title: Conditionals
1Conditionals
- Concepts
- Conditional execution
- if statement
- Conditional expressions
- Relational and logical operators
- Compound statements
2Control Flow
- Control flow is the order in which statements
are executed
Sequential control flow the next statement
executed is the next one that appears, in
order, in the C program
Conditional control flow choosing which of two
(or more) statements to execute before
continuing OR
choosing whether or not to skip a statement
before continuing
3Conditional Execution
- A conditional statement allows the computer to
choose an execution path depending on the value
of a variable or expression - if the withdrawal is more than the bank
balance, then print an error - if today is my birthday, then add one to my age
- if using whole milk, add two eggs, otherwise add
three eggs - if (condition) statement
- In parentheses is a condition, also called a
logical or Boolean expression - Made up of variables, constants, arithmetic
expressions, and the relational operators - Value of condition is TRUE (non-zero) and FALSE
(0)
4Complex Conditionals
- if I have at least 15 or you have at least 15,
then we can go to the movies - if the temperature is below 32 degrees and its
raining, then its snowing - if its not the case that its Saturday or
Sunday, then its a work day - We use Boolean operators to code complex
conditionals in C. ( !) - if (myMoneygt15.0 yourMoneygt15.0)
canGoToMovies TRUE
5Multiple Actions
- if theres more than one conditional action
- If your temperature is high, then you have a
fever and should take two aspirin and go to bed
and call in sick tomorrow - Compound Statement
- Groups together statements so that they are
treated as a single statement - BLOCK - if ( temperature gt 98.6 )
- printf ( You have a fever. \n )
- aspirin aspirin ? 2
- printf (Go to bed/n)
- printf (Sleep in tomorrow/n)
-
6if-else Control Flow
yes
balance gt withdrawal
no
balance balance - withdrawal dispense_funds (
withdrawal )
printf ( No money! \n )
/ arrive here whether condition is TRUE or FALSE
/
- NESTED IF with relational op
- if (( time gt 0.) (time lt 12.))
- printf(Good Morning)
- else if ((time gt 12.) (time lt 18.))
- printf(Good Afternoon)
- else if ((time gt 18) (time lt 24.))
- printf(Good Evening)
- else printf(Time is out of range)
7if-else Control Flow
NESTED IF with logical op if ( x 5 )
if ( y 5 ) printf ( Both are 5. \n )
else printf ( x is 5, but y is not. \n )
else if ( y 5 ) printf ( y is 5, but x is
not. \n ) else printf ( Neither is 5. \n )
- Consider
- this
- problem
- Print the tax based on income
8Direct Solution
if ( income lt 15000 ) printf( No tax.
) if ( income gt 15000 income lt 30000 )
printf(18 tax.) if ( income gt 30000
income lt 50000 ) printf(22
tax.) if ( income gt 50000 income lt 100000
) printf(28 tax.) if ( income
gt100000) printf(31 tax.)
- Mutually exclusive conditions - only one will be
true
9Cascaded ifs
if ( income lt 15000 )
if ( income lt 15000 ) printf( No tax )
printf( No tax ) else
else if ( income lt 30000 ) if ( income lt
30000 ) printf( 18
tax. ) printf( 18 tax. )
else if ( income lt 50000 ) else
printf( 22 tax. ) if ( income lt 50000 )
else if ( income lt 100000 )
printf( 22 tax. )
printf( 28 tax. ) else else if (
income lt 100000 ) printf( 31 tax.
) printf( 28 tax. ) else printf(
31 tax. ) Order is important.
Conditions are evaluated in order given.
10Warning Danger Ahead
- The idea of conditional execution is natural ,
intuitive, and highly useful - However...
- Programs can get convoluted and hard to
understand - There are syntactic pitfalls to avoid
- if ( x 10 )
- printf( x is 10 )
-
- Bug! is used instead of
- This is not a syntax error, so the program can
execute - The Worlds Last C Bug!
status check_radar ( ) if (status 1)
launch_missiles ( )
11Nested if vs. AND ()
if ( age lt 25 ) if ( sex M )
insurance_rate insurance_rate 2
if ( (age lt 25) (sex M) )
insurance_rate insurance_rate 2
- Suppose we want a while loop to terminate as
- soon as either x is 17 or x is 42
- Which is it?
- while (x!17 x!42)
- while (x!17 x!42)
- either way? something else?
- Truth tables and DeMorgans laws give us tools
for answering such questions
12Truth Tables
- A "truth table" lists all possible combinations
of values, and the result of each combination,
here P and Q stand for any conditional
expressions - P Q P Q P Q !P
- T T T T F
- T F F T F
- F T F T T
- F F F F T
int high_risk /NOT Example
/ high_risk (age lt 25 sex M )
if ( high_risk ) / Do nothing /
else printf ( Cheap rates. \n)
if ( ! high_risk ) printf ( Cheap
rates. \n)
13DeMorgans Laws
- DeMorgans laws help determine when two complex
conditions are equivalent - They state
- ! ( P Q ) is equivalent to ( !P !Q )
- ! ( P Q ) is equivalent to ( !P !Q )
- This applies for any Boolean expressions P and Q,
which might themselves be complex expressions
if ( ! (age lt 25 sex M ) )
printf ( Cheap rates. \n) is equivalent
to if ( age gt 25 sex ! M ) )
printf ( Cheap rates. \n) Is it?
14Proof of DeMorgan
- Is it really true that
- !(PQ) (!P !Q) ?
P Q (PQ) !(PQ) !P !Q (! P !Q) T
T T F F T F F
T
F
F
F
F
F
T
F
T
T
F
T
F
T
T
F
T
T
T
T
We wanted a while loop to terminate as soon as
either x is 17 or x is 42. I.e., loop should
terminate if (x17 x42) So the loop
condition is while ( ! (x17 x42)
Using DeMorgans laws, we can rewrite
as while (x ! 17 x ! 42) A truth table
would show that while (x ! 17 x ! 42) is
wrong!
15Repetition
- Sometimes we want to repeat a block of code.
This is called a loop. - A loop is a repeated (iterated)
- sequence of statements
- Like conditionals, loops (iteration) give us a
huge increase in the power of our programs - Alert loops are harder to master than if
statements - Even experienced programmers often make subtle
errors when writing loops
16Motivating Loops
- Problem add 4 numbers entered at the keyboard.
- int sumint x1, x2, x3, x4
- printf(Enter 4 numbers )scanf(dddd,
x1, x2, x3, x4)sum x1 x2 x3 x4 - This works perfectly!
- But... what if we had 14 numbers? or 40? or 4000?
- The key to using loops to solve a problem is to
discover steps that can be repeated - Our algorithm for adding four numbers had no
repeated statements at all - But it does have some repetition buried in it.
- Lets rework the algorithm to make the repetition
more explicit
17Add 4 Numbers, Repetitively
- int sum, x
- sum 0printf(Enter 4 numbers )
- scanf(d, x)sum sum x
- scanf(d, x)sum sum x
- scanf(d, x)sum sum x
- scanf(d, x)sum sum x
int sum, xint count sum 0printf(Enter 4
numbers) count 1while (count lt 4)
scanf(d, x)sum sum xcount count
1
18More general solution
int sum, x, count int number_inputs /
Number of inputs / sum 0printf(How many
numbers? )scanf(d, number_inputs)printf(
Enter d numbers , number_inputs) count
1while ( count lt number_inputs )
scanf(d, x) sum sum x count count
1 Problem Compute 7! What is 1 2 3
4 5 6 7? (seven factorial) x 1 2 3
4 5 6 7 printf ( d, x )
19Moving to a Loop
- Bite size pieces More Regular
As a loop - x 1 x 1 i 2
x 1 - x x 2 x x i i i 1
i 2 - x x 3 x x i i i 1
while ( i lt 7 ) - x x 4 x x i i i 1
x x i - x x 5 x x i i i 1
i i 1 - x x 6 x x i i i 1
- x x 7 x x i i i 1
x 1 i 2
yes
x x i i i 1
i lt 7 ?
no
20Tracing the Loop
/ What is 1 2 3 ...7 / x 1 / A
/ i 2 / B / while ( i lt 7 ) / C
/ x x i / D / i i 1 / E
/ / F / printf ( d, x ) / G /
line i x I lt7? A ? 1 B 2 1 C 2 1 T D 2 2 E 3 2
C 3 2 T ...................... C 6
120 T D 6 720 E 7 720 C 7 720 T D 7 5040 E
8 5040 C 8 5040 F G (Print 5040)
21Examples
- Double Your Money!
- / Suppose your 1,000 is earning interest at 5
per - year. How many years until you double your
money? / - my_money 1000.0 n 0
- while ( my_money lt 2000.0 )
- my_money my_money 1.05
- n n 1
-
- printf( My money will double in d years., n)
- Average Inputs
- printf ( Enter values to average, end with -1.0
\n) - sum 0.0 count 0 sentinel
- scanf ( lf, next )
- while ( next ! -1.0 )
- sum sum next
- count count 1
- scanf ( lf, next )
-
- if (count gt 0)
22A For Loop
- / What is 1 2 3 ... n ? /
- x 1
- i 2
- while ( i lt n )
- x x i
- i i1
-
- printf ( d, x )
x 1 for ( i 2 i lt n i i1 ) x
x i printf ( d, x)
- for ( initialization condition
update expression) - statement1
- statement2
- ...
23for Loop Control Flow
Initialization
yes
Condition
For Loop Body
Update Expression
no
- Any for loop can be written as a while loop
- These two loops mean exactly the same thing
- for (initialization condition
update) statement - initialization while (condition)
statement update
24a 2-D Figure
- How would you print the following diagram?
- ?
- ? ?
- ? ? ?
- ? ? ? ?
- ? ? ? ? ?
- For every row ( row 1, 2, 3, 4, 5 )
- Print row stars
- define ROWS 5
- ...
- int row, col
- for ( row 1 row lt ROWS row row 1 )
- for ( col 1 col lt row col col 1)
- printf( ? )
-
- printf( \n )
-
25Summary
- Conditional
- Complex conditions are useful in while loops, for
loops, if statements, and even in assignment
statements - Operators , , and ! are part of C
- TRUE and FALSE can be defined
- Truth tables and DeMorgans laws help evaluate
complex expressions - Iteration
- General pattern
- Initialize, test, do stuff, repeat . . .
- while and "for" are equally general in C
- Use for when initialize/test/update are closely
related and simple, especially when counting - Use ints in loop counters (use increment/decrement
) BUT - Don't combine these with other operators in
expressions! E.g., don't try - x y / (3 --x--)
- Switch expression
- Missing BREAK is a common problem
- Switch is a form of conditional statement
- Switch is suitable for multi-way conditions that
depend upon an integer (or char) value
26the SWITCH expression
- The switch expression is not a conditional
expression as it is in an if statement - Only an integer expression is allowed
- Most often, the expression is a single integer
variable - The value of the variable determines which case
is chosen
- month 6
- switch ( month )
- case 2 /
February / - days 28
- break
- case 9 /
September / - case 4 /
April / - case 6
/ June / - case 11 /
November / - days 30
- break
- default / All the rest have 31
.../ - days 31
-
- printf ( There are d days. \n , days )
27More on SWITCH
- switch on char is also legal
- char marital_status
- ...
- switch ( marital_status )
- case m
- case M
- printf ( Married \n )
- break int or char expression
- case s
- case S
- printf ( Single \n )
- break
- default
- printf ( Sorry, I dont recognize that code. \n
) -