Selection Statements Pseudocode Natural language mixed with programming code Ex: if the radius is negative the program display a message indicating wrong input; the program compute the area and display the result; 1
Use conditions Selection Statement Conditions are in Boolean expression The bool Type and Operators Compare two values, such as whether i is greater than j C++ provides six relational operators (also known as comparison operators) Can also compare character Operator Name Example Result < 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 == is equal to operator = is assignment operator 2
One-way if Statements if (booleanexpression) statement(s); if (radius >= 0) area = radius * radius * PI; printf("the area for the circle of %f radius is %f, radius, area); Boolean Expression false (radius >= 0) false true true Statement(s) area = radius * radius * PI; printf("the area for the circle of %f radius is %f, radius, area); (a) (b) Boolean Expression Enclosed in parentheses Outer parentheses required if ((i > 0) && (i < 10)) pritnf( i is an integer between 0 and 10 ); (a) Equivalent Braces can be omitted if the block contains a single statement if ((i > 0) && (i < 10)) printf( i is an integer between 0 and 10 ); (b) 3
Boolean Expression Adding a semicolon at the end of an if clause is a common mistake This mistake is hard to find, because it is not a compilation error or a runtime error, it is a logic error This error often occurs when you use the next-line block style if (radius >= 0); area = radius * radius * PI; printf("the area is %f", area); (a) Logic Error Equivalent if (radius >= 0) ; area = radius * radius * PI; printf("the area is %f", area); (b) Empty Body Logical Operators (Boolean Operators) Combination of several conditions Name Operator Description Not! Logical negation And && Logical conjunction Or Logical disjunction 4
Truth Table p!p true false false True Logical negation p1 p2 p1 p2 false false false false true true true false true true true true Logical disjunction p1 p2 p1 && p2 false false false false true false true false False true true true Logical conjunction Conditional Short-circuit AND operator p1 && p2 If p1 is false, p2 is not evaluated Short-circuit OR operator p1 p2 If p1 is true, p2 is not evaluated 5
Leap Year Write a program that lets the user enter a year and checks whether it is a leap year. A year is a leap year if it is divisible by 4 but not by 100 or if it is divisible by 400. So you can use the following Boolean expression to check whether a year is a leap year: (year % 4 == 0 && year % 100!= 0) (year % 400 == 0) Mathematics: x < y < z (x < y) &&(y < z) Conversion 6
The if... Statement if (booleanexpression) statement(s)-for-the-true-case; statement(s)-for-the-false-case; true Statement(s) for the true case Boolean Expression false Statement(s) for the false case Nested if Statements if (i > k) if (j > k) printf("i and j are greater than k ); printf("i is less than or equal to k ); 7
Multiple Alternative if Statements if (score >= 90.0) grade = 'A'; if (score >= 80.0) grade = 'B'; if (score >= 70.0) grade = 'C'; if (score >= 60.0) grade = 'D'; grade = 'F'; Equivalent if (score >= 90.0) grade = 'A'; if (score >= 80.0) grade = 'B'; if (score >= 70.0) grade = 'C'; if (score >= 60.0) grade = 'D'; grade = 'F'; Multiple if Statements The clause matches the most recent if clause in the same block. int i = 1; int j = 2; int k = 3; if (i > j) if (i > k) printf("a"); printf("b"); (a) Equivalent This is better with correct indentation int i = 1; int j = 2; int k = 3; if (i > j) if (i > k) printf("a"); printf("b") (b) 8
Multiple if Statements Nothing is printed from the preceding statement. To force the clause to match the first if clause, you must add a pair of braces: int i = 1; int j = 2; int k = 3; if (i > j) if (i > k) printf ("A ); printf( "B ); This statement prints B. Expression Statement if (number % 2 == 0) even = true; even = false; (a) Equivalent This is better bool even = number % 2 == 0; (b) if (even == true) printf("it is even."); (a) Equivalent This is better if (even) printf("it is even."); (b) 9
Common Errors in Selection Statements Forgetting Necessary Braces if (radius >= 0) area = radius * radius * PI; printf("the area is %f,area); if (radius >= 0) area = radius * radius * PI; printf("the area is %f,area); (a) Wrong (b) Correct Common Errors in Selection Statements Wrong Semicolon at the if Line Logic Error if (radius >= 0); area = radius * radius * PI; printf("the area is %f,area); Equivalent Empty Body if (radius >= 0) ; area = radius * radius * PI; printf("the area is %f,area); (a) (b) 10
Common Errors in Selection Statements Mistakenly Using = for == if (count = 1) printf( count is zero\n ); printf( count is not zero\n ); Common Errors in Selection Statements Redundant Testing of Boolean Values if (even == true) printf("it is even."); (a) Equivalent This is better if (even) printf("it is even."); (b) 11
Compute BMI BMI Interpretation below 16 serious underweight 16-18 underweight 18-24 normal weight 24-29 overweight 29-35 seriously overweight above 35 gravely overweight Compute Taxes 12
switch Statements Handle multiple conditions switch (status) case 0: compute taxes for single filers; case 1: compute taxes for married file jointly; case 2: compute taxes for married file separately; case 3: compute taxes for head of household; default: printf("errors: invalid status"); switch Statement Flow Chart status is 0 Compute tax for single filers break status is 1 Compute tax for married file jointly break status is 2 Compute tax for married file separatly break status is 3 Compute tax for head of household break default Default actions Next Statement 13
switch Statement Rules The switch-expression must yield a value of char, byte, short, or int type and must always be enclosed in parentheses. The value1,..., and valuen must have the same data type as the value of the switch-expression. The resulting statements in the case statement are executed when the value in the case statement matches the value of the switch-expression. Note that value1,..., and valuen are constant expressions, meaning that they cannot contain variables in the expression, such as 1 + x. switch (switch-expression) case value1: statement(s)1; case value2: statement(s)2; case valuen: statement(s)n; default: statement(s)-for-default; switch Statement Rules The keyword break is optional, but it should be used at the end of each case in order to terminate the remainder of the switch statement. If the break statement is not present, the next case statement will be executed. The default case, which is optional, can be used to perform actions when none of the specified cases matches the switch-expression. switch (switch-expression) case value1: statement(s)1; case value2: statement(s)2; case valuen: statement(s)n; default: statement(s)-for-default; The casestatements are executed in sequential order, but the order of the cases (including the default case) does not matter. However, it is good programming style to follow the logical sequence of the cases and place the default case at the end. 14
Fall-Through Behavior Multiple cases matched in switch statement that will be executed until a break or end of the switch is reached switch(ch) case a : printf(ch) case b : printf(ch); case c : printf(ch); Formatting Output Operator setprecision(n) fixed showpoint setw(width) left right Description sets the precision of a floating-point number displays floating-point numbers in fixed point notation causes a floating-point number to be displayed with a decimal point with trailing zeros even if it has no fractional part specifies the width of a print field justifies the output to the left justifies the output to the right 15
Operator Precedence How to evaluate 3 + 4 * 4 > 5 * (4 + 3) 1? Operator Precedence Evaluation an expression without parentheses, the operators are applied according to the precedence rule and the associativity rule Precedence rule: var++, var-- +, - (Unary plus and minus), ++var,--var (type) Casting! (Not) *, /, % (Multiplication, division, and remainder) +, - (Binary addition and subtraction) <, <=, >, >= (Comparison) ==,!=; (Equality) && (Conditional AND) Short-circuit AND (Conditional OR) Short-circuit OR =, +=, -=, *=, /=, %= (Assignment operator) 16
Associativity a b + c d is equivalent to ((a-b)+c)-d A=b+=c = 5 is equivalent to a =(b+=(c=5)) Reference Hanly, J (2010), Problem Solving and Program Design in C, Addison Wesley, 6 th Ed, Chapter 4 Deitel, P. 2012. C: How to Program. Pearson Education, Inc Liang, Y. D. 2007. Introduction to Programming with C++. Pearson Education, Inc. Chapter 3 17