Download presentation
Presentation is loading. Please wait.
Published byShanna Ramsey Modified over 8 years ago
1
C++ Programming Control Structures I (Selection)
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
3
Control Structures (continued)
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
5
Relational Operators (continued)
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
7
Comparing Characters
8
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
9
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";
10
Relational Operators and the string Type (continued)
13
Logical (Boolean) Operators and Logical Expressions (NOT)
16
Order of Precedence (continued)
17
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
18
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
19
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
20
One-Way Selection (continued)
22
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
23
Two-Way Selection (continued)
24
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
25 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 ;
26
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.
27
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 ;
28
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.
29
What output? and Why? int age; age = 20; if ( age == 16 ) { cout<< “Did you get driver’s license?” ; }
30
What output? and Why? int age; age = 30; if ( age < 18 ) cout<< “Do you drive?”; cout<< “Too young to vote”;
31
What output? and Why? int code; code = 0; if ( ! code ) cout<< “Yesterday”; else cout<<“Tomorrow”;
32
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.
33
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
35
Multiple Selections: Nested if (continued)
36
Comparing if…else Statements with a Series of if Statements
37
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
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
39
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.
40
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
41
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
44
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 252500 40, 601000 75, 100750 otherwise0
45
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.
46
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.
47
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 “); }
48
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
49
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.
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.