C Programming Control Structures I Selection Control Structures

  • Slides: 49
Download presentation
C++ Programming Control Structures I (Selection)

C++ Programming Control Structures I (Selection)

Control Structures • A computer can proceed: − In sequence − Selectively (branch) -

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

Control Structures (continued)

Control Structures (continued)

Relational Operators • A condition is represented by a logical (Boolean) expression that can

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

Relational Operators (continued)

Relational Operators (continued)

Relational Operators and Simple Data Types • You can use the relational operators with

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

Comparing Characters

Comparing Characters

Relational Operators and the string Type • Relational operators can be applied to strings

Relational Operators and the string 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

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

Relational Operators and the string Type (continued) • Suppose we have the following declarations: string string str 1 str 2 str 3 str 4 = = = "Hello"; "Hi"; "Air"; "Bill"; "Big";

Relational Operators and the string Type (continued)

Relational Operators and the string Type (continued)

Relational Operators and the string Type (continued)

Relational Operators and the string Type (continued)

Relational Operators and the string Type (continued)

Relational Operators and the string Type (continued)

Logical (Boolean) Operators and Logical Expressions (NOT)

Logical (Boolean) Operators and Logical Expressions (NOT)

Order of Precedence (continued)

Order of Precedence (continued)

Short-Circuit Evaluation • Short-circuit evaluation: evaluation of a logical expression stops as soon as

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) (grade == 'A') && (x >= 7) //Line 1 //Line 2

Selection: if and if. . . else • • • One-Way Selection Two-Way Selection

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

One-Way Selection • The syntax of one-way selection is: • The statement is executed

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

One-Way Selection (continued)

One-Way Selection (continued)

Two-Way Selection • Two-way selection takes the form: • If expression is true, statement

Two-Way Selection • Two-way selection takes the form: • If expression is true, statement 1 is executed; otherwise, statement 2 is executed − statement 1 and statement 2 are any C++ statements • else is a reserved word

Two-Way Selection (continued)

Two-Way Selection (continued)

Compound (Block of) Statement if (age > { cout << } else { cout

Compound (Block of) Statement if (age > { cout << } else { cout << } 18) "Eligible to vote. " << endl; "No longer a minor. " << endl; "Not eligible to vote. " << endl; "Still a minor. " << endl;

int car. Doors, driver. Age ; double premium, monthly. Payment ; . . .

int car. Doors, driver. Age ; double 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 ; 25

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.

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 # %d of the phone book”; cout<< volume ;

If--Else for a mail order Write a program to calculate the total price of

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. =Otherwise, The discount rate is 15% and the shipping is 5. 00 pounds.

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? ” ; }

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”;

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”;

Example • Write a program to ask a student for his grades in 3

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.

Multiple Selections: Nested if • Nesting: one control statement in another • An else

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

Multiple Selections: Nested if (continued)

Multiple Selections: Nested if (continued)

Comparing if…else Statements with a Series of if Statements

Comparing if…else Statements with a Series of if Statements

Example The Air Force has asked you to write a program to label aircrafts

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

Example Write a program to get the roots of a quadratic equation, given the

Example Write a program to get the roots of a quadratic equation, given the 3 coefficients a, b, and c, a x 2 + b x + c = 0 38

Writing Nested if Statements • Display one word to describe the int value of

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.

Conditional Operator (? : ) • Conditional operator (? : ) takes three arguments

Conditional Operator (? : ) • Conditional operator (? : ) takes three arguments − Ternary operator • Syntax for using the conditional operator: expression 1 ? expression 2 : expression 3 • If expression 1 is true, the result of the conditional expression is expression 2 − Otherwise, the result is expression 3

switch Structures • switch structure: alternate to if-else • switch (integral) expression is evaluated

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

Light bulbs Write a program to ask the user for the brightness of a

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

Program Write a C program to calculate the average of three test grades and

Program Write 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.

Write a C program that calculates bills for the Electricity company. There are 3

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.

Find The output int x = 10 + 8 / 3 * 2 +

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 “); }

Write a program that reports the content of a compressed-air cylinder based upon the

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 Content Orange Ammonia Brown Carbon Monoxide Yellow Hydrogen Green Oxygen

Using selection • Every Sunday through Thursday you go to class. − When it

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.