Programming in C DaleWeemsHeadington Chapter 5 Continued Selection

  • Slides: 45
Download presentation
Programming in C++ Dale/Weems/Headington Chapter 5 Continued Selection Control Structures 1

Programming in C++ Dale/Weems/Headington Chapter 5 Continued Selection Control Structures 1

Flow of Control l means the order in which program statements are executed THE

Flow of Control l means the order in which program statements are executed THE 3 POSSIBILITIES ARE: Sequential Selection Control Structure Repetition Control Structure 2

Selection statements are used to choose an action depending on the current situation in

Selection statements are used to choose an action depending on the current situation in your program as it is running 3

CONTROL STRUCTURES Use logical expressions which may include: 6 Relational Operators < <= >

CONTROL STRUCTURES Use logical expressions which may include: 6 Relational Operators < <= > >= == != 3 Logical Operators ! && || 4

In C++ the value 0 represents false ANY non-zero value represents true 5

In C++ the value 0 represents false ANY non-zero value represents true 5

What can go wrong here? float Average; float Total; int How. Many; . .

What can go wrong here? float Average; float Total; int How. Many; . . . Average = Total / How. Many; 6

Improved Version float Average, float Total; int How. Many; if ( How. Many >

Improved Version float Average, float Total; int How. Many; if ( How. Many > 0 ) { Average = Total / How. Many; cout << Average; } else cout << “No prices were entered”; 7

if. . . else SYNTAX if ( Expression ) Statement. A else Statement. B

if. . . else SYNTAX if ( Expression ) Statement. A else Statement. B NOTE: Statement. A and Statement. B each can be a single statement, a null statement, or a block. 8

if. . . else provides two-way selection between executing one of 2 clauses (the

if. . . else provides two-way selection between executing one of 2 clauses (the if clause or the else clause) TRUE if clause expression FALSE else clause 9

USE OF BLOCKS RECOMMENDED if ( Expression ) { “ if clause ” }

USE OF BLOCKS RECOMMENDED if ( Expression ) { “ if clause ” } else { “ else clause” } 10

int car. Doors, driver. Age ; float premium, monthly. Payment ; if ( (car.

int car. Doors, driver. Age ; float premium, monthly. Payment ; if ( (car. Doors == 4 ) && (driver. Age > 24) ) { premium = 650. 00 ; cout << “ LOW RISK “ ; } else { premium = 1200. 00 ; cout << “ HIGH RISK ” ; } monthly. Payment = premium / 12. 0 + 5. 00 ; 11

WHAT HAPPENS IF YOU OMIT BRACES? if ( (car. Doors == 4 ) &&

WHAT HAPPENS IF YOU OMIT BRACES? if ( (car. Doors == 4 ) && (driver. Age > 24) ) premium = 650. 00 ; cout << “ LOW RISK “ ; else premium = 1200. 00 ; cout << “ HIGH RISK ” ; monthly. Payment = premium / 12. 0 + 5. 00 ; COMPILE ERROR OCCURS. The “if clause” is the single statement following the if. 12

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

Braces can only be omitted when each clause is a single statement if ( Last_Initial <= ‘K’ ) volume = 1; else volume = 2; cout << “Look it up in volume # “ << volume << “ of NYC phone book”; 13

if. . . else for a mail order Assign value. 25 to Discount. Rate

if. . . else for a mail order Assign value. 25 to Discount. Rate and assign value 10. 00 to Ship. Cost if Purchase is over 100. 00 Otherwise, assign value. 15 to Discount. Rate and assign value 5. 00 to Ship. Cost Either way, calculate Total. Bill 14

These braces cannot be omitted if ( Purchase > 100. 00 ) { Discount.

These braces cannot be omitted if ( Purchase > 100. 00 ) { Discount. Rate =. 25 ; Ship. Cost = 10. 00 ; } else { Discount. Rate =. 15 ; Ship. Cost = 5. 00 ; } Total. Bill = Purchase * (1. 0 - Discount. Rate) + Ship. Cost ; 15

if statement is a selection of whether or not to execute a statement (which

if statement is a selection of whether or not to execute a statement (which can be a single statement or an entire block) TRUE statement expression FALSE 16

Terminating your program int number ; cout << “Enter a non-zero number ” ;

Terminating your program int number ; cout << “Enter a non-zero number ” ; cin >> number ; if (number == 0 ) { cout << “Bad input. Program terminated ”; return 1 ; } // otherwise continue processing 17

These are equivalent. Why? if (number == 0 ) {. if ( ! number

These are equivalent. Why? if (number == 0 ) {. if ( ! number ) {. . } Each expression is only true when number has value 0. 18

Each I/O stream has a state (condition) l An input stream enters fail state

Each I/O stream has a state (condition) l An input stream enters fail state when you try to read invalid input data try to open a file which does not exist try to read beyond the end of the file l An output stream enters fail state when you try to create a file with an invalid name try to create a file on a write-protected disk try to create a file on a full disk 19

How can you tell the state? l The stream identifier has value 0 when

How can you tell the state? l The stream identifier has value 0 when the stream is in fail state. l When you use a file stream, you should check on its state. 20

Checking on the state ofstream my. Outfile; my. Outfile. open (“A: \my. Out. dat”);

Checking on the state ofstream my. Outfile; my. Outfile. open (“A: \my. Out. dat”); if ( ! my. Outfile ) { cout << “File opening error. ” << “Program terminated. ” << endl; return 1; } // otherwise send output to my. Outfile 21

Write if or if. . else for each If Tax. Code is ‘T’, increase

Write if or if. . else for each If Tax. Code is ‘T’, increase Price by adding Tax. Rate times Price to it. If Code has value 1, read values for Income and Tax. Rate from my. Infile, and calculate and display Tax. Due as their product. If A is strictly between 0 and 5, set B equal to 1/A, otherwise set B equal to A. 22

Some Answers if (Tax. Code == ‘T’) Price = Price + Tax. Rate *

Some Answers if (Tax. Code == ‘T’) Price = Price + Tax. Rate * Price; if ( Code == 1) { my. Infile >> Income >> Tax. Rate; Tax. Due = Income * Tax. Rate; cout << Tax. Due; } 23

Remaining Answer if ( ( A > 0 ) && (A < 5) )

Remaining Answer if ( ( A > 0 ) && (A < 5) ) B = 1/A; else B = A; 24

What output? and Why? int Age; Age = 20; if ( Age = 16

What output? and Why? int Age; Age = 20; if ( Age = 16 ) { cout << “Did you get driver’s license? ” ; } 25

What output? and Why? int Age; Age = 30; if ( Age < 18

What output? and Why? int Age; Age = 30; if ( Age < 18 ) cout << “Do you drive? ”; cout << “Too young to vote”; 26

What output? and Why? int Code; Code = 0; if ( ! Code )

What output? and Why? int Code; Code = 0; if ( ! Code ) cout << “Yesterday”; else cout << “Tomorrow”; 27

What output? and Why? int Number; Number = 0; if ( Number = 0

What output? and Why? int Number; Number = 0; if ( Number = 0 ) cout << “Zero value”; else cout << “Non-zero value”; 28

Both the if clause and the else clause of an if. . . else

Both the if clause and the else clause of an if. . . else statement can contain any kind of statement, including another selection statement. 29

Multi-alternative selection is also called multi-way branching, and can be accomplished by using NESTED

Multi-alternative selection is also called multi-way branching, and can be accomplished by using NESTED if statements. 30

NESTED if statements if ( Expression 1 ) Statement 1 else if ( Expression

NESTED if statements if ( Expression 1 ) Statement 1 else if ( Expression 2 ) Statement 2. . . else if ( Expression. N ) Statement. N else Statement N+1 EXACTLY 1 of these statements will be executed. 31

NESTED if statements Each Expression is evaluated in sequence, until some Expression is found

NESTED if statements Each Expression is evaluated in sequence, until some Expression is found that is true. Only the specific Statement following that particular Expression is executed. If no Expression is true, the Statement following the final else is executed. Actually, the final else and final Statement are optional. If omitted, and no Expression is true, then no Statement is executed. AN EXAMPLE 32. . .

Multi-way branching if ( Credits. Earned >= 90 ) cout << “SENIOR STATUS “;

Multi-way branching if ( Credits. Earned >= 90 ) cout << “SENIOR STATUS “; else if ( Credits. Earned >= 60 ) cout << “ JUNIOR STATUS “; else if ( Credits. Earned >= 30 ) cout << “ SOPHOMORE STATUS “; else cout << “ FRESHMAN STATUS “; 33

Writing NESTED if statements Display one word to describe the int value of Number

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. 34

One answer if (Number > 0) cout << “Positive”; else if (Number < 0)

One answer if (Number > 0) cout << “Positive”; else if (Number < 0) cout << “Negative”; else cout << “Zero”; 35

Other answer if ( Index < 35 ) cout << “Pleasant”; else if (

Other answer if ( Index < 35 ) cout << “Pleasant”; else if ( Index <= 60 ) cout << “Unpleasant”; else cout << “Health Hazard”; 36

Write a void function called Display. Message ( ) which you can call from

Write a void function called Display. Message ( ) which you can call from main ( ) to describe the pollution index value it receives as a parameter. Your city describes a pollution Index less than 35 as “Pleasant”, 35 through 60 as “Unpleasant”, and above 60 as “Health Hazard. ” 37

void Display. Message( int Index ) { if ( Index < 35 ) cout

void Display. Message( int Index ) { if ( Index < 35 ) cout << “Pleasant”; else if ( Index <= 60 ) cout << “Unpleasant”; else cout << “Health Hazard”; } 38

THE REST OF THE PROGRAM #include <iostream. h> void Display. Message (int); // declare

THE REST OF THE PROGRAM #include <iostream. h> void Display. Message (int); // declare function int main (void) { int Pollution. Index; // declare variable } cout << “Enter air pollution index”; cin >> Pollution. Index; Display. Message(Pollution. Index); // call return 0; 39

Using selection Every Monday thru Friday you go to class. When it is raining

Using selection Every Monday thru Friday 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. 40

// program tells how to spend your day #include < iostream. h > void

// program tells how to spend your day #include < iostream. h > void main ( void ) { int Day; char Raining; cout << “Enter day (use 1 for Sunday)”; cin >> Day; cout << “Is it raining? (Y/N)”; cin >> Raining; 41

} if ( ( Day == 1) || (Day == 7) ) // Sat

} if ( ( Day == 1) || (Day == 7) ) // Sat or Sun { if (Raining == ‘Y’) cout << “Read in bed”; else cout << “Have fun outdoors”; } else { cout << “Go to class ”; if (Raining == ‘Y’) cout << “Take an umbrella”; } 42

In the absence of braces, an else is always paired with the closest preceding

In the absence of braces, an else is always paired with the closest preceding if that doesn’t already have an else paired with it. 43

Bad Example has output: FAIL float Average; Average = 100. 0; 100. 0 Average

Bad Example has output: FAIL float Average; Average = 100. 0; 100. 0 Average if ( Average >= 60. 0 ) if ( Average < 70. 0 ) cout << “Marginal PASS”; else cout << “FAIL”; WHY? The compiler ignores indentation and pairs the else with the second 44 if.

To correct the problem, use braces float Average; Average = 100. 0; 100. 0

To correct the problem, use braces float Average; Average = 100. 0; 100. 0 Average if ( Average >= 60. 0 ) { if ( Average < 70. 0 ) cout << “Marginal PASS”; } else cout << “FAIL”; 45