c++ programming control structures i (selection)

58
C++ Programming Control Structures I (Selection)

Upload: mitchell-patterson

Post on 27-Dec-2015

247 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: C++ Programming Control Structures I (Selection)

C++ Programming

Control Structures I (Selection)

Page 2: C++ Programming Control Structures I (Selection)

C++ Programming: From Problem Analysis to Program Design, Fourth Edition 2

Control Structures

• A computer can proceed:− In sequence

− Selectively (branch) - making a choice

− Repetitively (iteratively) - looping

• Some statements are executed only if certain conditions are met

• A condition is met if it evaluates to true

Page 3: C++ Programming Control Structures I (Selection)

C++ Programming: From Problem Analysis to Program Design, Fourth Edition 3

Control Structures (continued)

Page 4: C++ Programming Control Structures I (Selection)

C++ Programming: From Problem Analysis to Program Design, Fourth Edition 4

Relational Operators

• A condition is represented by a logical (Boolean) expression that can be true or false

• Relational operators: − Allow comparisons

− Require two operands (binary)

− Evaluate to true or false

Page 5: C++ Programming Control Structures I (Selection)

C++ Programming: From Problem Analysis to Program Design, Fourth Edition 5

Relational Operators (continued)

Page 6: C++ Programming Control Structures I (Selection)

C++ Programming: From Problem Analysis to Program Design, Fourth Edition 6

Relational Operators and Simple Data Types

• You can use the relational operators with all three simple data types:− 8 < 15 evaluates to true− 6 != 6 evaluates to false− 2.5 > 5.8 evaluates to false− 5.9 <= 7.5 evaluates to true

Page 7: C++ Programming Control Structures I (Selection)

C++ Programming: From Problem Analysis to Program Design, Fourth Edition 7

Comparing Characters

Page 8: C++ Programming Control Structures I (Selection)

C++ Programming: From Problem Analysis to Program Design, Fourth Edition 8

Relational Operators and thestring Type• Relational operators can be applied to strings

• Strings are compared character by character, starting with the first character

• Comparison continues until either a mismatch is found or all characters are found equal

• If two strings of different lengths are compared and the comparison is equal to the last character of the shorter string

− The shorter string is less than the larger string

Page 9: C++ Programming Control Structures I (Selection)

C++ Programming: From Problem Analysis to Program Design, Fourth Edition 9

Relational Operators and thestring Type (continued)• Suppose we have the following declarations:

string str1 = "Hello";

string str2 = "Hi";

string str3 = "Air";

string str4 = "Bill";

string str4 = "Big";

Page 10: C++ Programming Control Structures I (Selection)

C++ Programming: From Problem Analysis to Program Design, Fourth Edition 10

Relational Operators and thestring Type (continued)

Page 11: C++ Programming Control Structures I (Selection)

C++ Programming: From Problem Analysis to Program Design, Fourth Edition 11

Relational Operators and thestring Type (continued)

Page 12: C++ Programming Control Structures I (Selection)

C++ Programming: From Problem Analysis to Program Design, Fourth Edition 12

Relational Operators and thestring Type (continued)

Page 13: C++ Programming Control Structures I (Selection)

C++ Programming: From Problem Analysis to Program Design, Fourth Edition 13

Logical (Boolean) Operators and Logical Expressions (NOT)

Page 14: C++ Programming Control Structures I (Selection)
Page 15: C++ Programming Control Structures I (Selection)
Page 16: C++ Programming Control Structures I (Selection)

C++ Programming: From Problem Analysis to Program Design, Fourth Edition 16

Order of Precedence

• Relational and logical operators are evaluated from left to right

• The associativity is left to right• Parentheses can override precedence

Page 17: C++ Programming Control Structures I (Selection)

C++ Programming: From Problem Analysis to Program Design, Fourth Edition 17

Order of Precedence (continued)

Page 18: C++ Programming Control Structures I (Selection)

C++ Programming: From Problem Analysis to Program Design, Fourth Edition 18

Order of Precedence (continued)

Page 19: C++ Programming Control Structures I (Selection)

C++ Programming: From Problem Analysis to Program Design, Fourth Edition 19

Order of Precedence (continued)

Page 20: C++ Programming Control Structures I (Selection)

C++ Programming: From Problem Analysis to Program Design, Fourth Edition 20

Order of Precedence (continued)

Page 21: C++ Programming Control Structures I (Selection)

C++ Programming: From Problem Analysis to Program Design, Fourth Edition 21

Short-Circuit Evaluation

• Short-circuit evaluation: evaluation of a logical expression stops as soon as the value of the expression is known

• Example:

(age >= 21) || ( x == 5) //Line 1

(grade == 'A') && (x >= 7) //Line 2

Page 22: C++ Programming Control Structures I (Selection)

C++ Programming: From Problem Analysis to Program Design, Fourth Edition 22

Selection: if and if...else

• One-Way Selection• Two-Way Selection• Compound (Block of) Statements• Multiple Selections: Nested if• Comparing if...else Statements with a

Series of if Statements

Page 23: C++ Programming Control Structures I (Selection)

C++ Programming: From Problem Analysis to Program Design, Fourth Edition 23

One-Way Selection

• The syntax of one-way selection is:

• The statement is executed if the value of the expression is true

• The statement is bypassed if the value is false; program goes to the next statement

• if is a reserved word

Page 24: C++ Programming Control Structures I (Selection)

C++ Programming: From Problem Analysis to Program Design, Fourth Edition 24

One-Way Selection (continued)

Page 25: C++ Programming Control Structures I (Selection)

C++ Programming: From Problem Analysis to Program Design, Fourth Edition 25

One-Way Selection (continued)

Page 26: C++ Programming Control Structures I (Selection)
Page 27: C++ Programming Control Structures I (Selection)

C++ Programming: From Problem Analysis to Program Design, Fourth Edition 27

One-Way Selection (continued)

Page 28: C++ Programming Control Structures I (Selection)

C++ Programming: From Problem Analysis to Program Design, Fourth Edition 28

Two-Way Selection

• Two-way selection takes the form:

• If expression is true, statement1 is executed; otherwise, statement2 is executed− statement1 and statement2 are any C++

statements

• else is a reserved word

Page 29: C++ Programming Control Structures I (Selection)

C++ Programming: From Problem Analysis to Program Design, Fourth Edition 29

Two-Way Selection (continued)

Page 30: C++ Programming Control Structures I (Selection)

C++ Programming: From Problem Analysis to Program Design, Fourth Edition 30

Two-Way Selection (continued)

Page 31: C++ Programming Control Structures I (Selection)

C++ Programming: From Problem Analysis to Program Design, Fourth Edition 31

Two-Way Selection (continued)

Page 32: C++ Programming Control Structures I (Selection)

C++ Programming: From Problem Analysis to Program Design, Fourth Edition 32

Compound (Block of) Statement

if (age > 18){

cout << "Eligible to vote." << endl;cout << "No longer a minor." << endl;

} else{

cout << "Not eligible to vote." << endl;cout << "Still a minor." << endl;

}

Page 33: C++ Programming Control Structures I (Selection)

33

int carDoors, driverAge ;

double premium, monthlyPayment ;

. . .

if ( (carDoors == 4 ) && (driverAge > 24) ) {

premium = 650.00 ;

cout<<“ LOW RISK “ ;}

else {

premium = 1200.00 ;

cout <<“HIGH RISK ” ; }

monthlyPayment = premium / 12.0 + 5.00 ;

Page 34: C++ Programming Control Structures I (Selection)

34

What happens if you omit braces?

if ( (carDoors == 4 ) && (driverAge > 24) )

premium = 650.00 ;

cout<< “ LOW RISK “ ;

else

premium = 1200.00 ;

cout<< “ HIGH RISK ” ;

monthlyPayment = premium / 12.0 + 5.00 ;

COMPILE ERROR OCCURS. The “if clause” is the single statement following the if.

Page 35: C++ Programming Control Structures I (Selection)

35

Braces can only be omitted when each clause is a single statement

if ( lastInitial <= ‘K’ )

volume = 1;

else

volume = 2;

Cout<< “Look it up in volume # %d of the phone book”;cout<< volume ;

Page 36: C++ Programming Control Structures I (Selection)

36

If--Else for a mail order

Write a program to calculate the total price of a certain purchase. There is a discount and shipping cost:

The discount rate is 25% and the shipping is 10.00 if purchase is over 100.00.Otherwise, The discount rate is 15% and the shipping is 5.00 pounds.

Page 37: C++ Programming Control Structures I (Selection)

37

What output? and Why?

int age;

age = 20;

if ( age == 16 )

{

cout<< “Did you get driver’s license?” ;

}

Page 38: C++ Programming Control Structures I (Selection)

38

What output? and Why?

int age;

age = 30;

if ( age < 18 )

cout<< “Do you drive?”;

cout<< “Too young to vote”;

Page 39: C++ Programming Control Structures I (Selection)

39

What output? and Why?

int code;

code = 0;

if ( ! code )

cout<< “Yesterday”;

else

cout<<“Tomorrow”;

Page 40: C++ Programming Control Structures I (Selection)

40

Example

• Write a program to ask a student for his grades in 3 exams ( each out of 50 ) , get their total and inform the student whether he passed or failed the course.

Page 41: C++ Programming Control Structures I (Selection)

C++ Programming: From Problem Analysis to Program Design, Fourth Edition 41

Multiple Selections: Nested if

• Nesting: one control statement in another• An else is associated with the most recent if that has not been paired with an else

Page 42: C++ Programming Control Structures I (Selection)
Page 43: C++ Programming Control Structures I (Selection)

C++ Programming: From Problem Analysis to Program Design, Fourth Edition 43

Multiple Selections: Nested if (continued)

Page 44: C++ Programming Control Structures I (Selection)

C++ Programming: From Problem Analysis to Program Design, Fourth Edition 44

Comparing if…else Statements with a Series of if Statements

Page 45: C++ Programming Control Structures I (Selection)

45

Example

The Air Force has asked you to write a program to label aircrafts as military or civilian. Your program input is the plane’s speed and its estimated length. For planes traveling faster than 1100 km/hr, you will label those shorter than 52 m “military”, and longer as “Civilian”. For planes traveling less than 1100, you will issue an “aircraft unknown” statement.

Page 46: C++ Programming Control Structures I (Selection)

46

Example

Write a program to get the roots of a quadratic equation, given the 3 coefficients a, b, and c,

a x2 + b x + c = 0

Page 47: C++ Programming Control Structures I (Selection)

Writing Nested if Statements

• Display one word to describe the int value of number as “Positive”, “Negative”, or “Zero”

• Your city classifies a pollution index − less than 35 as “Pleasant”, − 35 through 60 as “Unpleasant”,− and above 60 as “Health Hazard.” − Display the correct description of the− pollution index value.

Page 48: C++ Programming Control Structures I (Selection)

Using selection

• Every Sunday through Thursday you go to class.− When it is raining you take an umbrella.

• But on the weekend, what you do depends on the weather.− If it is raining you read in bed. Otherwise, you

have fun outdoors.

Page 49: C++ Programming Control Structures I (Selection)

C++ Programming: From Problem Analysis to Program Design, Fourth Edition 49

Conditional Operator (?:)

• Conditional operator (?:) takes three arguments− Ternary operator

• Syntax for using the conditional operator:expression1 ? expression2 : expression3

• If expression1 is true, the result of the conditional expression is expression2− Otherwise, the result is expression3

Page 50: C++ Programming Control Structures I (Selection)

C++ Programming: From Problem Analysis to Program Design, Fourth Edition 50

switch Structures

• switch structure: alternate to if-else

• switch (integral) expression is evaluated first

• Value of the expression determines which corresponding action is taken

• Expression is sometimes called the selector

Page 51: C++ Programming Control Structures I (Selection)
Page 52: C++ Programming Control Structures I (Selection)

C++ Programming: From Problem Analysis to Program Design, Fourth Edition 52

switch Structures (continued)

• One or more statements may follow a case label

• Braces are not needed to turn multiple statements into a single compound statement

• The break statement may or may not appear after each statement

• switch, case, break, and default are reserved words

Page 53: C++ Programming Control Structures I (Selection)
Page 54: C++ Programming Control Structures I (Selection)

Light bulbs

Write a program to ask the user for the brightness of a light bulb (in Watts), and print out the expected lifetime:

Brightness Lifetime in hours

25 2500

40, 60 1000

75, 100 750

otherwise 0

Page 55: C++ Programming Control Structures I (Selection)

ProgramWrite a C program to calculate the average

of three test grades and print out a report

with the student’s ID number, average,

and how well is the student progress.

“Very Good” is a 70-point average or

better, “Good” is an average between 60

and 70, and “Failing” is 50 point average

or less.

Page 56: C++ Programming Control Structures I (Selection)

Write a C program that calculates bills for the Electricity company. There are 3 types of customers: residential (code R) , commercial (code C) , and Industrial (code I).

- For a code R customer, the bill is $10 plus $0.05 for each kilowatt used.

- For a code C customer, the bill is $1000 for the first 2000 kilowatt, and $0.005 for each additional kilowatt used.

- For a code I customer, the bill is $1000 if he used less than 4000 kilowatt, $2000 if he used between 4000 and 10000 kilowatt, or $3000 if he used more than 10000 kilowatt.

The inputs of the program should be the type of customer ( R C or I) and the kilowatts used. The output should be the amount of money the customer has to pay.

Page 57: C++ Programming Control Structures I (Selection)

Find The output

int x = 10 + 8 / 3 * 2 + 10 ;switch ( x ) {case 21: printf ( “ Eeny “ ) ; break;case 24: printf ( “ Meeny “ ) ;break;case 25 : printf ( “ Miny “ ) ; break;case 28 : printf ( “ Mo “ ) ; break;default : printf(“ None of them “); }

Page 58: C++ Programming Control Structures I (Selection)

Write a program that reports the content of a compressed-air cylinder based upon the first letter of the cylinder’s color. The program input is a character representing the observed color of the cylinder: ‘Y’ or ‘y’ for yellow, ‘G’ or ‘g’ for green and so on. Given:

 Color ContentOrange AmmoniaBrown Carbon MonoxideYellow HydrogenGreen Oxygen