C++ Programming Control Structures I (Selection)
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)
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 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
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: string str1 = "Hello"; string str2 = "Hi"; string str3 = "Air"; string str4 = "Bill"; string str4 = "Big";
Relational Operators and the string Type (continued)
Logical (Boolean) Operators and Logical Expressions (NOT)
Order of Precedence (continued)
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
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 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)
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
Two-Way Selection (continued)
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; }
25 int carDoors, driverAge ; double premium, monthlyPayment ;... if ( (carDoors == 4 ) && (driverAge > 24) ) { premium = ; cout<<“ LOW RISK “ ; } else { premium = ; cout <<“HIGH RISK ” ; } monthlyPayment = premium / ;
What happens if you omit braces? if ( (carDoors == 4 ) && (driverAge > 24) ) premium = ; cout<< “ LOW RISK “ ; else premium = ; cout<< “ HIGH RISK ” ; monthlyPayment = premium / ; 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 ( lastInitial <= ‘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 a certain purchase. There is a discount and shipping cost: The discount rate is 25% and the shipping is if purchase is over Otherwise, The discount rate is 15% and the shipping is 5.00 pounds.
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 ) cout<< “Do you drive?”; cout<< “Too young to vote”;
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 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 is associated with the most recent if that has not been paired with an else
Multiple Selections: Nested if (continued)
Comparing if…else Statements with a Series of if Statements
37 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.
38 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
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 −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
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 bulb (in Watts), and print out the expected lifetime: BrightnessLifetime in hours , , otherwise0
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 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 kilowatt, or $3000 if he used more than 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 = / 3 * ; 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 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: ColorContent OrangeAmmonia BrownCarbon Monoxide YellowHydrogen GreenOxygen
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.