BITG 1223: Selection Control Structure by: ZARITA (FTMK) LECTURE 4 (Sem 1, 16/17) 1
Learning Outcomes At the end of this lecture, you should be able to: 1. Explain the concept of selection control structure 2. Use relational and logical operators 3. Use if, if..else, if..else if, switch..case, and nested if statements and conditional operators in program. 2
Control Structures Program is written using simple control structures to determine the flow of program execution. Three types of control structure: sequential, selection, repetition. SEQUENTIAL is a series of statements that execute one after another. statement 1 statement 2 statement 3. 3
Control Structures. SELECTION (branch) - is used to execute one set of statements if a given condition is TRUE, a different set of statements, or no statements at all, is executed if the condition is FALSE. statement set 1 condition statement set 2. 4
3. SYSTEM DESIGN continued Control Structures REPETITION (loop) - is used to execute a set of statements repeatedly as long as a given condition is TRUE.. Condition. statement set 5
The logic flow of Control Structures Sequential Selection false? true? : boolean expression Repetition? true false? : boolean expression 6
Why Selection? Selection structure allows the program to select an action (statements to execute), based upon a condition. For example, by using an if statement to check the password entered, your program can decide whether or not a user is allowed access to the program. The condition in this example is a valid password. Condition is evaluated (checked and determined) to be either true or false. 7
Understand TRUE and FALSE The operator will assign 1 if the evaluation is true, or 0 if the evaluation is false. true or false is known as boolean value (bool). An expression (program code that has a value) that has a boolean value is called a boolean expression. Thus, a condition is a boolean expression. 8
Boolean Expression There are a number of operators that allow checks on condition. There are two types of operators that could be used in boolean expression: relational operators and logical operators. Expression with a relational operator is called relational expression, and with logical operator is called logical expression. Relational and logical expressions are both boolean expressions, and can be used as condition. 9
Relational Operators Used to compare between two values. Operator Meaning Relational Result Expression < less than 1 < 2 true < = less than or equal to 1 < = 2 true > greater than 1 > 2 false > = greater than or equal to 1 > = 2 false = = equal to 1 = = 2 false! = not equal to 1! = 2 true 10
Relational Operators More examples: Assume int y=6, x=5; Relational Operators Sample Relational Expression Value > y > x T < y < 2 F > = x > = 3 T < = y < = x F = = x = = 5 T! = y! = 6 F 11
Logical Operators Used to combine two or more relational expressions into one. && AND New relational expression is true if both expressions are true expression1 && expression 2 OR New relational expression is true if either expression is true expression1 expression2! NOT Reverses the value of an expression; true expression becomes false, false expression becomes true! expression 12
Logical Operators Truth table for boolean expression A B A&&B A B!A!B 0 0 0 0 1 1 0 1 0 1 1 0 1 0 0 1 0 1 1 1 1 1 0 0 13
Logical Operator && (AND) Example : Assume int x = 4, y = 5, z = 8; expression1 expression2 expression1 && expression2 Sample Expression F F F ( y > 10) && ( z < =x ) F T F ( z < = y) && ( x = = 4) T F F ( y! = z) && ( z < x ) T T T ( z > = y ) && ( x! = 3) 14
Logical Operator (OR) Example : Assume int x = 4, y = 5, z = 8; expression1 expression2 expression1 expression2 Sample Expression F F F ( y > 10) ( z < = x ) F T T ( z < = y) ( x = = 4) T F T ( y! = z) ( z < x ) T T T ( z > = y ) ( x! = 3 ) 15
Logical Operator! (NOT) Example : Assume int x = 50 expression! expression Sample Expression F T! (x = = 60) T F! (x! = 60) 16
Precedence of Logical Operator Highest! && Lowest Example: (2 < 3) (5 > 6) && (7 > 8) 2 is true because AND is evaluated before OR 1 17
More on Operator Precedence Example: Highest Lowest Arithmetic operators Relational operators Logical operators 8 < 2 + 7 5 == 6 is true 1 2 3 4 16
Boolean Expressions Can be assigned to a variable Example : bool result = (x <= y); bool flag = true; Assigns 0 for false, 1 for true Do not get confused between: = (assignment) and == (equal to) 19
Checking Numeric Ranges with Boolean Operators Used to test if a value is within a range if (grade >= 0 && grade <= 100) cout << "Valid grade"; Can also test if a value lies outside a range if (grade < 0 grade > 100) cout << "Invalid grade"; Cannot use mathematical notation if (0 <= grade <= 100) //Doesn t //work! 20
Notes on expression An arithmetic expression that evaluates to a nonzero number is a true boolean expression. An arithmetic expression that evaluates to zero is a false boolean expression. 21
Selection Control Structure Single way Two way : using if statement : using if else statement, or using conditional operator Multiple way : using if else if statement, or using switch case statement Nested if 22
The if Statement Use to code a single way selection structure Allows statements to be conditionally executed, or skipped over Models the way we mentally evaluate situations. Example: If it is cold outside, wear a coat and wear a hat. 23 4-23
Structure of if statement NO ; after condition if (condition) { statement_1; statement_2; statement_n; } condition true 1 or more statements false If (condition) is true, then the statement(s) in the body are executed. If (condition) is false, then the statement(s) are skipped. The block of statements within the { } is called the body of the if statement. If 24 there is only ONE statement in the body, the { } may be omitted.
Things to REMEMBER about if Statement DO NOT place ; after (condition) Don't forget the { } around a multistatement body Place each statement on a separate line after (condition), and indent it. (condition) : 0 means false; any other value means true 25 4-25
Example of if statement Example : To calculate and print the value of a. If a<10, then a is multiplied with b. false Start Read a a<10 Print a Stop true a =a*b int main() { } int a, b = 5; cin >> a; if (a < 10) a = a * b; cout<<a; return 0; 26
More Example: if Statement if (score >= 60) cout << "You passed.\n"; if (score >= 90) { grade = 'A'; cout << "Wonderful job!\n"; } REMEMBER : If there are > 1 statements in the body, MUST use { } 27 4-27
More Example: if Statement Look at the use of condition in if statement: bool validmonths; int months; double numofpayment,total; cin >> months >> total; if (months < 0) validmonths = false; if (validmonths) numofpayment = total / months; 28 4-28
The if..else Statement Use to code a two way selection structure Allows a choice of execution between statements depending on whether (condition) is true or false Models the way we mentally evaluate situations Example : If it is raining, take an umbrella, else, take a hat. 29 4-29
Structure of if else statement if (condition) { statement set 1; } else { statement set 2; } true statement set 1 condition false statement set 2 If (condition) is true, statement set 1 is executed and statement set 2 is skipped. If (condition) is false, statement set 1 is skipped and statement set 2 is executed. 30
Example of if else statements Example: To determine odd or even number Start int main() { false Read a a%2==0 true Print a, is an odd number Print a, is an even number int a; cin >> a; if (a % 2 = = 0) cout<< a << is an even number ; else cout << a << is an odd number ; Stop } return 0; 31
More Example: if..else Statements if (score >= 60) cout << "You passed.\n"; else cout << "You did not pass.\n"; if (intrate > 0) { interest = loanamt * intrate; cout << interest; } else cout << "You owe no interest.\n"; 32 4-32
Example of if else statements discount = 0; if (price<100); else discount = price *0.3 ; same as discount = 0; if (!(price<100)) discount = price *0.3 ; else ; same as discount = 0; if (!(price<100)) discount = price *0.3 ; 33
Example of if else statements (with errors!) if (score<40) cout<< Failed ; cout<< Work Harder ; else cout<< Passed ; cout<< Congratulations ; same as if (score<40) cout<< Failed ; cout<< Work Harder ; else Notes : error! else without matching if cout<< Passed ; cout<< Congratulations ; 34
The Conditional Operator Can use to create short if/else statements Format: expr? expr : expr; x<0? y=10 : z=20; First Expression: Expression to be tested 2nd Expression: Executes if first expression is true 3rd Expression: Executes if the first expression is false 35
The Conditional Operator The value of a conditional expression is The value of the second expression if the first expression is true The value of the third expression if the first expression is false Parentheses () may be needed in an expression due to precedence of boolean operator 36
Program example: Conditional Operator 37
The if..else if Statement Use to code a multiple way selection structure Chain of if statements that a condition is tested in order until one condition is found to be true Also models thought processes Example : If it is raining, take an umbrella, else, if it is windy, take a hat, else, if it is sunny, take sunglasses. 38 4-38
Structure of if else if statement if(condition1) { statement set 1 } else if(condition2) { statement set 2 } else if(condition3) { statement set 3 } else statement set4 condition1 f condition2 f condition3 f Statement set 4 t t t Statement set 1 Statement set 2 Statement set 3 39
From the previous slide If (condition1) is true, statement set 1 is executed and the rest of the statement sets are skipped. But If (condition1) is false, statement set 1 is skipped. Next check on (condition2). If (condition2) is true, statement set 2 is executed and the rest of the statement sets are skipped. But If (condition2) is false, statement set 2 is skipped. Next check on (condition3). If (condition3) is true, statement set 3 is executed and the rest of the statement sets are skipped. But If (condition3) is false, statement set 3 is skipped. Statement set 4 is executed. 40
Example of multiple way selection (using if..else if statement) Example: To determine and print a student s grade from the test mark. Start Read student s test mark; mark mark >=90 && mark <= 100 true Print Grade A false mark >=80 && mark < 90 true Print Grade B false 1 2 41
1 2 mark >= 70 && mark <80 true Print Grade C false mark >= 60 && mark < 70 false mark >= 0 && mark <60 false Print Not a valid input true true Print Grade D Print Grade F Stop 42
int main( ) { int mark; char Grade; cout << Please enter the test mark for a student : ; cin >> mark; if (mark >=90 && mark <= 100) cout << Gred A ; else if (mark >=80 && mark < 90) cout << Gred B ; else if (mark >= 70 && mark <80) cout << Gred C ; else if (mark >= 60 && mark < 70) cout << Gred D ; else if (mark >= 0 && mark <60) cout << Gred F ; else cout << Not a valid input. ; } 43
More Example : if..else if if (age >= 21) cout << "Adult"; else if (age >= 13) cout << "Teen"; else if (age >= 2) cout << "Child"; else cout << "Baby"; 44 4-44
Multiple way selection using switch..case statement must be either bool value, integer types, or a character 45
Structure of Multiple way selection using switch..case statement 46
47
switch (mark/10) { case 10 : case 9 : grade = A ; break; case 8 : grade = B ; break; case 7 : grade = C ; break; case 6 : grade = D ; break; Example of switch case 5 : case 4 : case 3 : case 2 : case 1 : case 0 : grade = F ; break; default : } 48
switch (selection) Example of switch { case 'A' : cout << "\n To append a record" << endl; break; case 'M' : cout << "\n To modify a record" << endl; break; case 'D' : cout << "\n To delete a record" << endl; break; case 'X' : cout << "\n To exit the menu" << endl; break; default : cout << "\n Invalid selection" << endl; } 49
Menu-Driven Program Menu: list of choices presented to the user on the computer screen Menu-driven program: program execution controlled by user selecting from a list of actions Menu can be implemented using if..else if or switch..case statements 50 4-50
Menu-driven Program Organization Display list of numbered or lettered choices for actions. Input user s selection of number or letter Test user selection in (condition) If match, then execute code to carry out desired action if not, then test with next (condition) 51 4-51
Nested if Statements Is an if statement that is part of the if or else part of another if statement Can be used to evaluate more then 1 conditions. Example : To set the grade to A, score is between 90 and 100 if (score < 100) { // The second if is a nested if that resides in the if part of the first if. if (score > 90) grade = 'A'; } 52 4-52
Notes on Coding Nested ifs An else matches the nearest if that does not have an else if (score < 100) if (score > 90) grade = 'A'; else... // goes with second if, // not first one Proper indentation helps you to understand the codes. 53 4-53
Nested if statement false true false true 54
if (job_title == 'a') // a = associate professor if (year_served > 5) if (no_of_publications > 7) cout << "\npromote to Professor" endl; else cout << "\nmore publications required" << endl; else cout << "\nmore service required" << endl; else cout << "\nmust become associate professor first" << endl; Example of nested if code 55
Dangling else in nested if statement false true false true 56
Example of dangling else in nested if if (score>40) if (mark==100) cout << "\nfull mark. Congratulations." << endl; else cout << "\nfailed. Must work harder" << endl; SAME AS if (score>40) { if (mark==100) cout << "\nfull mark. Congratulations." << endl; else cout << "\nfailed. Must work harder" << endl; } 57
Solution of dangling else in nested if statement Dangling else solution 58
Example: Solution of dangling else in nested if if (score>40) { } else if (mark==100) cout << "\nfull mark. Congratulations." << endl; cout << "\nfailed.must work harder" << endl; - THE END - 59