c/c++ programming for engineers: branching ( decision …i109/notes/4 - branching.pdfwith the code...

19
7/12/2018 1 C/C++ Programming for Engineers: Branching ( Decision Making ) John T. Bell Department of Computer Science University of Illinois, Chicago 2 Review What operation will be executed first? X = A + B / C * D – E % F; A. A will get stored in X B. A will get added to B C. B will get divided by C D. C will get multiplied by D E. E will get divided by F, and remainder used.

Upload: others

Post on 29-May-2020

1 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: C/C++ Programming for Engineers: Branching ( Decision …i109/Notes/4 - Branching.pdfwith the code in that case. •Execution continues until a “break” is encountered, or the end

7/12/2018

1

C/C++ Programming for Engineers:Branching ( Decision Making )

John T. Bell

Department of Computer ScienceUniversity of Illinois, Chicago

2

Review

What operation will be executed first?

X = A + B / C * D – E % F;

A. A will get stored in X

B. A will get added to B

C. B will get divided by C

D. C will get multiplied by D

E. E will get divided by F, and remainder used.

Page 2: C/C++ Programming for Engineers: Branching ( Decision …i109/Notes/4 - Branching.pdfwith the code in that case. •Execution continues until a “break” is encountered, or the end

7/12/2018

2

3

Review

What will be stored by:

double X;

X = 3 / 5 * 3.14 + 1.0 * 3 / 5;

A. 0

B. 0.6

C. 0.6 + pi

D. 0.6 pi

E. 0.6 ( pi + 1 )

4

Relational OperatorsEvaluate to true ( 1 ) or false ( 0 )

Operator, by example Meaning / Result

A < B True if A is less than B, false otherwise.

A > B True if A is greater than B, false otherwise.

A <= B True if A is less than or equal to B, false otherwise.

A >= B True if A is greater than or equal to B, false otherwise.

A == B True if A is equal to B, false otherwise.

A != B True if A is not equal to B, false otherwise.

Page 3: C/C++ Programming for Engineers: Branching ( Decision …i109/Notes/4 - Branching.pdfwith the code in that case. •Execution continues until a “break” is encountered, or the end

7/12/2018

3

5

Points to Note Regarding Relational Operators

• The operators <=, >=, ==, and != use two characters each, with no space in between.

• Relational operators have lower precedence than + or -, but higher than assignment, and are evaluated left to right.

– ( <, >, <=, and >= have equal precedence, higher than == and!=, which are equal to each other. )

• There is no ≤, ≥, or ≠ on the keyboard!

6

Simple Branching with if-else

• Syntax:

if( condition ) {

// True code here

} else {

// False code here

}

• Note: else { } clause is optional.

Page 4: C/C++ Programming for Engineers: Branching ( Decision …i109/Notes/4 - Branching.pdfwith the code in that case. •Execution continues until a “break” is encountered, or the end

7/12/2018

4

7

Notes Regarding the “condition”

• Most commonly a relational operator:if( A < B ) { . . .

• Can also be a variable of type “bool”:bool greater = A > B;

if( greater ) { . . .

• In practice, any non-zero is considered true:if ( X ) { . . .

// “True” if X != 0

8

Notes Regarding the Braces

• The braces are not technically required.

• If they are omitted, then only a single line is under control of the if ( or else. )

• This can often lead to errors:

if( denominator == 0 )

cout << “Error: Denominator is zero!\n”;

exit( -1 ); // Not in if. Always exits.

Page 5: C/C++ Programming for Engineers: Branching ( Decision …i109/Notes/4 - Branching.pdfwith the code in that case. •Execution continues until a “break” is encountered, or the end

7/12/2018

5

9

DANGER! DANGER!Don’t Confuse == with =

• The following code is perfectly legal, will usually compile without errors or warnings, but does not do as expected:

if( percentage = 100.0 ) {

cout << “The job is done!” << endl;

return 0;

}

10

What will happen if you make this mistake?

if( percentage = 100.0 ) {

cout << “The job is done!” << endl;

return 0;

}

A. The code will execute only when “percentage” equals 100.0, and “percentage” will remain unchanged.

B. “percentage” will become 100.0, but the code will only execute if it was already 100.0 to begin with.

C. “percentage” will become 100.0, and the code will execute every time.

D. Syntax error – The program will not compile.E. Execution error – The program will crash when it gets to this

code.

Page 6: C/C++ Programming for Engineers: Branching ( Decision …i109/Notes/4 - Branching.pdfwith the code in that case. •Execution continues until a “break” is encountered, or the end

7/12/2018

6

11

Avoid Testing Floating Point Numbers for Equality, Due to Round-Off Errors

• Wrong:if( X == Y ) { . . .

• Better:if( fabs( X – Y ) < tolerance ) { . . .

• Where tolerance is very small, e.g. 1.0E-6

• Note: This problem may be situation dependent.

12

Logical OperatorsEvaluate Compound Conditions

Operator, by example Meaning / Result

A && B True if A is true AND B is also true, false otherwise.

A || B True if either A is true OR B is true, false otherwise.

! A NOT A. True if A is false, false otherwise.

• && has lower precedence than relational operators.• || has lower precedence than &&, but higher than assignment.• ! has higher precedence than anything else we have seen.• DANGER! DANGER! Do not confuse && with &, or || with |.

Page 7: C/C++ Programming for Engineers: Branching ( Decision …i109/Notes/4 - Branching.pdfwith the code in that case. •Execution continues until a “break” is encountered, or the end

7/12/2018

7

13

Summary of Precedence of ( Relational and Logical ) Operators

Operators Description Example Associativity

( ) Parentheses ! ( age > 21 ) NA

! - NOT, unary minus if( ! done ) { . . . Right to Left

* / % Multiply, Divide, Mod

Left to Right

+ - Add, Subtract

< <= > >= Relational X + Y < P * Q

== != Equality X > 0 == Y > 0

&& AND

|| OR X != 0 || X == 0 && Y == 0

= += -= *= /= %= Assignment done = error < tolerance; Right to Left

14

When is Leap Year ?

int year;

bool leapYear;

year = . . . ; // Assume this gets a value.

leapYear = year % 4 == 0;// check precedence

leapYear = ( ( ( year % 4 == 0 )

&& ( year % 100 != 0 ) )

|| ( year % 400 == 0 ) );

leapYear = !( year % 4 ) && year % 100

|| !( year % 400 );// Poor style

Page 8: C/C++ Programming for Engineers: Branching ( Decision …i109/Notes/4 - Branching.pdfwith the code in that case. •Execution continues until a “break” is encountered, or the end

7/12/2018

8

15

How do you check if X is between 0 and 10 ?

A. if( 0.0 < X < 10.0 )

B. if( 0.0 <= X <= 10.0 )

C. if( 0.0 < X && X < 10.0 )

D. if( 0.0 <= X && X <= 10.0 )

E. if( 0.0 < X || X < 10.0 )

16

Which of these is equivalent to ! green == red

A. ! ( green == red )

B. ( ! green ) == red

C. green = ! red

D. green += red

E. red == green

Page 9: C/C++ Programming for Engineers: Branching ( Decision …i109/Notes/4 - Branching.pdfwith the code in that case. •Execution continues until a “break” is encountered, or the end

7/12/2018

9

17

Using an “if” to Reject Bad Input

int age;

cout << “How old are you? ”;

cin >> age;

if( age < 0 || age > 120 ) {

cout << “I’m sorry, ” << age << “can’t be right.\n”

<< “Please try again.\n”;

exit( 0 );

}

Notes:• It is good practice to report the bad data. ( Better to explain why it is bad. )• It is not sufficient to print an error message. You must deal with the problem.• Later we will learn how to repeat the question until they provide good input.

18

Combined Ifs

• Either the true or false clauses of an if may contain any other code, including other ifs.

• When the true clause of an if contains another if, it is termed “nested”.

• When the false clause of an if contains another if, it is termed “sequential”. It is not uncommon to see long strings of sequential ifs.

Page 10: C/C++ Programming for Engineers: Branching ( Decision …i109/Notes/4 - Branching.pdfwith the code in that case. •Execution continues until a “break” is encountered, or the end

7/12/2018

10

19

A Nested If Example

if( X <= 0.0 ) {

if( X < 0.0 ) {

cout << “Negative”;

} else {

cout << “Zero”;

}

} else {

cout << “Positive”;

}

20

A Sequential If Example

if( X < 0.0 ) {

cout << “Negative”;

} else if( X > 0.0 ) {

cout << “Positive”;

} else {

cout << “Zero”;

}

Page 11: C/C++ Programming for Engineers: Branching ( Decision …i109/Notes/4 - Branching.pdfwith the code in that case. •Execution continues until a “break” is encountered, or the end

7/12/2018

11

21

A Longer Sequential If Example

if( score >= 90.0) {

cout << “A”;

} else if( score >= 80.0) {

cout << “B”;

} else if( score >= 70.0) {

cout << “C”;

} else if( score >= 60.0) {

cout << “D”;

} else {

cout << “F”;

}

Note that the order of the tests is important in this example, and that the braces are not technically needed.

22

In a series of sequential ifs,How many clauses will be executed?

A. Every one that is true.

B. The first one that is true.

C. One of the true ones, but which one may be machine and compiler dependent.

D. An error will occur if more than one clause is true.

E. The first one if it is true, otherwise none at all.

Page 12: C/C++ Programming for Engineers: Branching ( Decision …i109/Notes/4 - Branching.pdfwith the code in that case. •Execution continues until a “break” is encountered, or the end

7/12/2018

12

23

Preview

Which of the following operators is very similar to an if-else?

A. <=

B. ==

C. !=

D. ?=

E. ?:

24

Consider a case where a variable is checked against a list of choices:

char direction; cout << “Which way to move, NSEW ?”;cin >> direction;

if( direction == ‘W’ ) // Go WestX -= 1;

else if ( direction == ‘E’ ) // EastX += 1;

else if ( direction == ‘N’ ) // NorthY += 1;

else if( direction == ‘S’ ) // SouthY -= 1;

elsecout << “Illegal Move.\n”;

switch( direction ) {case ‘W’:

X -= 1;break;

case ‘E’:X += 1;break;

case ‘N’:Y += 1;break;

case ‘S’:Y -= 1;break;

default:cout << “Illegal Move. \n”;

}

Page 13: C/C++ Programming for Engineers: Branching ( Decision …i109/Notes/4 - Branching.pdfwith the code in that case. •Execution continues until a “break” is encountered, or the end

7/12/2018

13

25

General Syntax of Switch

switch( expression ) {case const_expr1 :

// code block 1break;

.

.

.default:

// default code}

Repeat for more cases

expression evaluates to integer at run time

const expressions evaluate to integersat compile time

break is ( semi ) optional.See next slide

default is optional.

26

Notes Regarding Switch

• The switch expression is first evaluated, and then compared against the constant expressions, one by one in the order given.

• As soon as a match is found, execution proceeds with the code in that case.

• Execution continues until a “break” is encountered, or the end of the switch is reached.

• The default case is executed if and only if none of the constant expressions matched the switch expression ( and a default case is present. )

Page 14: C/C++ Programming for Engineers: Branching ( Decision …i109/Notes/4 - Branching.pdfwith the code in that case. •Execution continues until a “break” is encountered, or the end

7/12/2018

14

27

Execution “falls through” when the break statement is omitted

switch( direction ) {case ‘W’:case ‘w’:

X -= 1;case ‘E’:

X += 1;break;

case ‘N’:Y += 2;

case ‘S’:Y -= 1;cout << “Vertical\n”;break;

default:cout << “Illegal Move. \n”;

}

Useful for combining cases. Here the capital ‘W’ case does nothing, and then falls through to lower case ‘w’

Error here. The missing break causes ‘w’ to continue into ‘E’, negating its work.

“Clever” here. The missing break causes “Vertical” to be printed for both ‘N’ and ‘S’. Note that Y had to be incremented by 2 in ‘N’ to compensate.

breaks jump down here, after the closing }

28

String Comparisons

• C++ has a “string” data type, useful for holding strings of characters. (Words, lines, paragraphs.)

• strings can be compared lexicographically, using ==, !=, <, <=, >, and >= operators.

• strings are compared character by character, using the ASCII codes, until a pair of characters does not match or the end of the string is reached.

• Case matters. ‘A’ to ‘Z’ are all smaller than ‘a’, so “Zoology” comes before ( is less than ) “apples”.

Page 15: C/C++ Programming for Engineers: Branching ( Decision …i109/Notes/4 - Branching.pdfwith the code in that case. •Execution continues until a “break” is encountered, or the end

7/12/2018

15

29

Conditional Operator

• Most operators are either unary or binary, i.e. they take either one or two operands.

• C++ has one special operator, termed the conditional operator, which is a ternary operator, meaning it takes 3 operands.

• By itself, the conditional operator is shown as ?:

• In practice, the syntax is:operand_1 ? operand_2 : operand_3

30

Functionality of The Conditional Operator

• If the first operand is “true”, the result is the second operand. Otherwise the third operand.

• This lets it work like an if-else:

• ?: precedence is the same as assignment, evaluated right to left. ( Second operand is always considered as if in parentheses. )

if( x < 0 )sign = -1;

elsesign = 1;

sign = ( x < 0 ) ? -1 : 1;Equivalent

( ) shown for clarity, but not needed.

Page 16: C/C++ Programming for Engineers: Branching ( Decision …i109/Notes/4 - Branching.pdfwith the code in that case. •Execution continues until a “break” is encountered, or the end

7/12/2018

16

31

More conditional notes

• The results of the conditional operator can be used in larger expressions:

pay = base + ( ( sales > quota ) ? 1.0 : 0.5 ) * bonus;

• Conditional expressions can be nested like ifs:sign = x > 0.0 ? 1.0 : ( x < 0.0 ? -1.0 : 0.0 );

32

Review

Which of the following C++ operators has the lowest precedence?

A. *B. +C. !D. *=E. !=

Page 17: C/C++ Programming for Engineers: Branching ( Decision …i109/Notes/4 - Branching.pdfwith the code in that case. •Execution continues until a “break” is encountered, or the end

7/12/2018

17

33

Review

Which of the following C++ operators has the highest precedence?

A. *B. +C. !D. *=E. !=

34

Exercises

• Use the conditional operator to find the larger of X and Y, and store it in a variable “max”:

omax = X > Y ? X : Y;

• Now use a nested conditional to store the larger of X, Y, and Z in max:

omax = X > Y ? ( X > Z ? X : Z ) : ( Y > Z ? Y : Z );

Page 18: C/C++ Programming for Engineers: Branching ( Decision …i109/Notes/4 - Branching.pdfwith the code in that case. •Execution continues until a “break” is encountered, or the end

7/12/2018

18

C/C++ Programming for Engineers:Decision Making with Different Data Types

John T. Bell

Department of Computer ScienceUniversity of Illinois, Chicago

36

Boolean ( bool ) Variables

• The bool data type “remembers” True/False values for later use.

• Example: bool done = false;while( !done ) { . . .

if( some condition )done = true;

• Example: bool converged;converged = abs( error ) < tolerance;

Page 19: C/C++ Programming for Engineers: Branching ( Decision …i109/Notes/4 - Branching.pdfwith the code in that case. •Execution continues until a “break” is encountered, or the end

7/12/2018

19

37

Character ( char ) Tests

• #include <cctype>

• Recall zero is considered false, non-zero is true;

• int isalpha( char c ); // True if c in a-z, A-Z

• int isdigit( char c ); // True if c in 0-9

• int isspace( char c ); // True if c is space, tab, /n

• char toupper( char c ); // Converts a-z to A-Z

• char tolower( char c ); // Converts A-Z to a-z

• See http://www.cplusplus.com/reference/cctype/

38

String Comparisons

• Two Strings can be compared with ==, !=, <, >, <=, or >=

• Example: if ( answer == “yes” )

• Strings are compared character by character until a pair are different or one string ends.

• ASCII code: A-Z all come before a-z:

• cat == cat != Cat• catapult < caterpillar

• cat < catastrophe• Zebra < aardvark