1 conditions logical expressions selection control structures chapter 5

Post on 01-Jan-2016

229 Views

Category:

Documents

2 Downloads

Preview:

Click to see full reader

TRANSCRIPT

1

ConditionsLogical Expressions

Selection Control Structures

Chapter 5

2

The Judge says, "Listen up!"

Who was George Boole andwill he help me decide anything?

IF I cannot figure this out,

THEN I will smash this infernal machine !

3

Flow of Control

Defn => The order in which the computer executes statements in a program

Control StructureStatements are normally executed in a sequential

flowControl structure statements alter the normal,

sequential flow

4

Selection or Branching Statements

Cause the computer to choose between two alternative actions

?

stmt 1 stmt 2

FalseTrue

5

Logical Expressions

Also called “Boolean” expressionsUsually the “condition” which is checkedExamples:

?

stmt 1 stmt 2

FalseTrue

6

Boolean Data

Some languages (Pascal) have a Boolean type with actual values TRUE and FALSE

C and C++ accomplish this with int values FALSE with the int value 0 (zero) TRUE with any nonzero value

Does anything get printed?

7

A Boolean Constant

It is possible to create your own Boolean constants

Use another preprocessor statement, the #define

Is anything printed?

8

Relational Operators

Used to evaluate how quantities are relatedTypically they are mathematical inequality

symbols < > <= >=

Note => =<Some variations in C

equal = =not equal !=

Examples

9

Logical Operators

Used to combine logical (Boolean) expressionsOperators

AND use &&OR use ||NOT use !

&& and || are binary operatorstwo operands

! is a unary operatorone operand

Is anything printed?

10

Short-Circuit Evaluation

ConsiderIf the first condition is FALSE, no need to check

second condition (why?)if we do check the second, it is a run time error

(why?)

“Short-circuit evaluation”evaluate in L to R orderevaluation stops as soon as final truth value can be

determined

11

Precedence of Operators

!* / %+ -< <= > >== = ! =&& | | =

High precedence

Low precedence

See also page A1, Appendix B

12

Changing English Statements to Logical Expressions

We say “x greater than 10 and less than 20”But

Computer Syntax is different

13

Proper Logical Expressions

We are really wanting to AND two comparisons(x greater than 10) AND (x less than 20)

Is anything printed?

14

Interesting Phenomenon with Floating Point Values

Calculated values may be algebraically equal but evaluate differently

This is due to conversion to and from binary, internal round off.

15

Relational Operators with Floating Point Values

Do not compare floating point numbers for equality Operands for = = must match bit for binary bit Algebraically equal is not bitwise equal Instead, compare for closeness

16

The If-Else Form

Note the syntaxThe condition expression is usually a comparisonIt must be enclosed in parenthesesC++ does not use the “then” key wordSemicolons ; follow statements

if (abs (n1 - n2) < 0.0001)cout << "close" << endl;

elsecout << "not equal" << endl;

if (abs (n1 - n2) < 0.0001)cout << "close" << endl;

elsecout << "not equal" << endl;

?

stmt 1 stmt 2

FalseTrue

17

Blocks -- Compound Statements

For the “then” or “else” portion of the statement we may wish multiple statements

Use curly brackets around the block of statements

if (abs (n1 - n2) < 0.0001) {

cout << "may not be equal but, " ;cout << "close" << endl;

} else

cout << "not equal" << endl;

if (abs (n1 - n2) < 0.0001) {

cout << "may not be equal but, " ;cout << "close" << endl;

} else

cout << "not equal" << endl;

18

The If (only) Form

The “else” portion is optionalIf the condition is false

nothing is done?

stmt 1

FalseTrue

if (n1 == n2) cout << "equal" << endl;

if (n1 == n2) cout << "equal" << endl;

Example:

19

A Common Mistake

Using the = operator (assignment)instead of the = = (comparison for equality)

Actual result … 5 assigned to x, then that true value used to determine path through the if statement

if (x = 5) cout << “ x = 5”;else cout << “x not equal to 5”;

if (x = 5) cout << “ x = 5”;else cout << “x not equal to 5”;

What gets printed?

20

The Nested IF

IF

21

Nested IF

Syntax calls for a “statement” after the if ( … )

That statement can be any kind of statement(List statements we know about)

It can be an if statementcoutcinassignmentif

if (x < 7) if (y > 5) cout << “hi mom”;

if (x < 7) if (y > 5) cout << “hi mom”;

22

The Dangling Else

How to determine which if the else goes withExample:

if (abs (x - 7)) if (x < 7) cout << “x approaches 7 from left”; else cout << “x approaches 7 from the right”; else cout << “x not close to 7”;

if (abs (x - 7)) if (x < 7) cout << “x approaches 7 from left”; else cout << “x approaches 7 from the right”; else cout << “x not close to 7”;

Rule : An else goes with the closest unmatched if

?

?

23

The Dangling Else

Rule : an else goes with the closest unmatched if

Consider … how do you force an else to go with a previous if?

if (x < y)

if (y > 3) cout << “message about y > 3”; else cout << “message about x and y”;

if (x < y)

if (y > 3) cout << “message about y > 3”; else cout << “message about x and y”;

if (x < y)

{ if (y > 3) cout << “message about y > 3”; } else cout << “message about x and y”;

if (x < y)

{ if (y > 3) cout << “message about y > 3”; } else cout << “message about x and y”;

Use { curly brackets } to nest the statements

24

Testing the State of an I/O Stream

The name of the input stream (used by itself) returns a valuereturns a 0 if it is NOT successfulit returns a NON zero value if it IS successful

25

Testing the State of an I/O Stream

When reading a file (a named input stream) we wish to know when it reaches the end

Since the name returns a 0 or non-0, this can be used as a Boolean value

Used to control program sequencing, control a file reading loop

26

Algorithm Walk-Through

Checking an algorithm (module) for correctnessWrite down what is supposed to be true

before an algorithm runsafter the algorithm runs

Check the source code to make sure these pre- and post-conditions are as specified

27

Implementation Phase

Use a “code walkthrough”think of it as “playing computer”execute the module by hand, changing values, etc. to

verify

Use an execution traceuse the watch window

Test control structuresuse data, program options that will execute each

branch of the program at least once

28

Testing and Debugging Hints

Beware of confusingthe assignment = with the equals = =the bitwise & with the logical &&the bitwise | with the logical | |

Use <= or >=, NEVER =< or =>Don’t forget { } around blocks of statements

controlled by an if or an elseEcho print input data, test for bad data

top related