Presentation is loading. Please wait.

Presentation is loading. Please wait.

CHAPTER 4 Selection CSEG1003 Introduction to Computing

Similar presentations


Presentation on theme: "CHAPTER 4 Selection CSEG1003 Introduction to Computing"— Presentation transcript:

1 CHAPTER 4 Selection CSEG1003 Introduction to Computing
By Eng Pei Chee Lecturer, Dep. Of Electrical & Electronics Engineering, Southern College

2 Objectives: To write expressions using:
comparison operator conditional operator logical operators (&&, ||, and !) To examine the rules governing operator precedence To generate random numbers using the rand() method To implement selection control using: if if-else switch

3 4.1 Comparison Operators (Relational Operator)
Boolean data (/Logical data): 2 possible values: LOGIC true (non-zero) or false (0) In OLD C, there is no Boolean data type Boolean data type provided since ASNI C99 via stdbool.h To output Boolean, treat it as int %d

4 4.1 Comparison Operators (Relational Operator)
Six comparison operators:

5 4.1 Comparison Operators (Relational Operator)

6 Check Point 3.1 List six comparison operators.
<, <=, ==, !=, >, >= 3.2 Show the printout of the following statements: printf("%d\n", 'a' < 'b'); // true printf("%d\n", 'a' <= 'A'); // false printf("%d\n", 'a' > 'b'); // false printf("%d\n", 'a' >= 'A'); // true printf("%d\n", 'a' == 'a'); // true printf("%d\n", 'a' != 'b'); // true

7 4.2 Logical Operators (Boolean Operator)
The logical operators !, &&, ||, and ^ can be used to create a compound Boolean expression.

8 4.2 Logical Operators (Boolean Operator)
Truth Table: NOT operator, ! negates true to false and false to TRUE.

9 4.2 Logical Operators (Boolean Operator)
Truth Table: AND operator, && Result is TRUE if and only if both operators is TRUE.

10 4.2 Logical Operators (Boolean Operator)
Truth Table: OR operator , || Result is TRUE if at least one of the operators is TRUE.

11 4.2 Logical Operators (Boolean Operator)
Truth Table: Exclusive OR operator , ^ Result is TRUE if and only if the two operands have different Boolean values.

12 4.2 Logical Operators (Boolean Operator)
Example: LogicalOperator.java

13 4.2 Logical Operators (Boolean Operator)
CAUTION: In mathematic, following expression is correct: But is incorrect in C Correct expression in C:

14 Check Point (true) && (3 > 4) false !(x > 0) && (x > 0) false
3.18 Assuming that x is 1, show the result of the following Boolean expressions. (true) && (3 > 4) false !(x > 0) && (x > 0) false (x > 0) || (x < 0) true (x != 0) || (x == 0) true (x >= 0) || (x < 0) true (x != 1) == !(x == 1) true

15 Check Point ((x > 1) && (x < 100)) || (x < 0)
3.19 Write a Boolean expression that evaluates to true if a number stored in variable num is between 1 and 100. (x > 1) && (x < 100) 3.20 Write a Boolean expression that evaluates to true if a number stored in variable num is between 1 and 100 or the number is negative. ((x > 1) && (x < 100)) || (x < 0) 3.21 Assume that x and y are int type. Which of the following are legal Java expressions? x > y > 0 incorrect x = y && y incorrect x /= y correct x or y incorrect x and y incorrect (x != 0) || (x = 0) incorrect

16 Check Point 3.22 Suppose that x is 1. What is x after the evaluation of the following expression? a. (x >= 1) && (x++ > 1) a. x is 2. b. (x > 1) && (x++ > 1) b. x is 1. 3.23 What is the value of the expression ch >= 'A' && ch <= 'Z' if ch is 'A', 'p', 'E', or '5'? If ch is 'A', the expression is true; If ch is 'p', the expression is false; If ch is 'E', the expression is true; If ch is '5', the expression is false;

17 Check Point 3.25 Write a Boolean expression that evaluates true if age is greater than 13 and less than 18. age > 13 && age < 18 3.26 Write a Boolean expression that evaluates true if weight is greater than 50 pounds or height is greater than 60 inches. weight > 50 || height > 60. 3.27 Write a Boolean expression that evaluates true if weight is greater than 50 pounds and height is greater than 60 inches. weight > 50 && height > 60. 3.28 Write a Boolean expression that evaluates true if either weight is greater than 50 pounds or height is greater than 60 inches, but not both. weight > 50 ^ height > 60.

18 4.3 Operators Precedence & Associativity
high low

19 4.3 Operators Precedence & Associativity
Operator associativity: If operators with the same precedence are next to each other, their associativity determines the order of evaluation. Left-associative: evaluate from left to right all operators (except assignment) Right-associative: Evaluate from right to left assignment operator

20 4.3 Operators Precedence & Associativity
Determine the order in which operators are evaluated How to evaluate 3 + 4 * 4 > 5 * (4 + 3) - 1 3 + 4 * 4 > 5 * 7 – 1 > 5 * 7 – 1 > 35 – 1 19 > 35 – 1 19 > 34 (1) Inside parentheses first (2) multiplication (3) multiplication (4) addition (5) subtraction (6) Greater than Answer is false

21 Check Point 3.39 List the precedence order of the Boolean operators. Evaluate the following expressions: true || true && false true && true || false The precedence order for boolean operators is ^, &&, and || true || true && false is true true && true || false is true 3.40 True or false? All the binary operators except = are left associative. True.

22 Check Point 3.41 Evaluate the following expressions:
2 * > 2 && 4 – 2 > 5 false 2 * > 2 || 4 – 2 > 5 false 3.42 Is (x > 0 && x < 10) the same as ((x > 0) && (x < 10))? Is (x > 0 || x < 10) the same as ((x > 0) || (x < 10))? Is (x > 0 || x < 10 && y < 0) the same as (x > 0 || (x < 10 && y < 0))? All Yes.

23

24 4.3 If statement if statement: Syntax & flowchart: One-way
executes the statements if the condition is true. Syntax & flowchart:

25 4.3 If statement Example 1: ComputeAreaIf.java
Compute the area if radius ≥ 0, otherwise, the two statements in the block will not be executed.

26 4.3 If statement Block braces can be omitted if they enclose a single statement. Omitting braces makes the code shorter, but it is prone to errors. It is a common mistake to forget the braces when you go back to modify the code that omits the braces.

27 4.3 If statement Example 2: A program that prompts the user to enter an integer. If the number is a multiple of 5, the program displays HiFive. If the number is divisible by 2, it displays HiEven.

28 4.3 If statement Example 2: A program that prompts the user to enter an integer. If the number is a multiple of 5, the program displays HiFive. If the number is divisible by 2, it displays HiEven.

29 Check Point 3.4 Write an if statement that assigns 1 to x if y is greater than 0. if (y > 0) x = 1; 3.5 Write an if statement that increases pay by 3% if score is greater than 90. if (score > 90) pay *= 1.03;

30 4.4 If-Else statement If-else statement: Syntax & flowchart: Two-way
Decides which statements to execute based on whether the condition is true or false. Syntax & flowchart:

31 4.4 If-Else statement Example 1: ComputeAreaIfElse.java
Prompt the user for the radius. Compute the area if radius ≥ 0, otherwise, a message "Negative input" is displayed.

32 4.4 If-Else statement Example 1: ComputeAreaIfElse.java
Prompt the user for the radius. Compute the area if radius ≥ 0, otherwise, a message "Negative input" is displayed.

33 4.4 If-Else statement Example 2: EvenOdd.java
Prompt an integer number from the user. Checks whether the number is even or odd

34 4.4 If-Else statement Example 2: EvenOdd.java
Prompt an integer number from the user. Checks whether the number is even or odd

35 Check Point 3.6 Write an if statement that increases pay by 3% if score is greater than 90, otherwise increases pay by 1%. if (score > 90) pay *= 1.03; else pay *= 1.01;

36 Check Point 3.7 What is the printout of the code in (a) and (b) if number is 30? What if number is 35? Number value (a) (b) 30 30 is even 30 is odd 35 35 is odd

37 4.5 Nested If statement Nested if:
An if statement can be inside another if statement to form a nested if statement. An else clause is matched to the last unmatched if (no matter what the indentation implies) Braces can be used to specify the if statement to which an else clause belongs

38 4.5 Nested If & Multi-way If-Else statement
Example: Nested if (layman term) if ( the time is after 7 pm){ if ( you have a book) read the book; else watch TV; } else{ go for a walk;

39 4.5 Nested If & Multi-way If-Else statement
Example: Nested if if ( i > k ){ if (j > k) printf("i and j are greater than k\n"); } else printf("i is less than or equal to k\n"); The if (j > k) statement is nested inside the if (i > k) statement if ( i > k && j > k){ printf("i and j are greater than k\n“); } else{ printf("i is less than or equal to k\n"); If statement uses logical AND operator

40 4.5 Nested If & Multi-way If-Else statement

41 4.5 Nested If & Multi-way If-Else statement

42 Check Point 3.8 Suppose x = 3 and y = 2; show the output, if any, of the following code. What is the output if x = 3 and y = 4? What is the output if x = 2 and y = 2? Draw a flowchart of the code. Note: else matches the first if clause. No output if x = 3 and y = 2. Output is “z is 7” if if x = 3 and y = 4. Output is “x is 2” if if x = 2 and y = 2.

43 Check Point 3.9 Suppose x = 2 and y = 3. Show the output, if any, of the following code. What is the output if x = 3 and y = 2? What is the output if x = 3 and y = 3? (Hint: Indent the statement correctly first.) No output if x = 2 and y = 3. Output is “x is 3” if x = 3 and y = 2. Output is “z is 6” if x = 3 and y = 3.

44 Check Point 3.10 What is wrong in the following code?
Consider score is 90, what will be the grade?

45 4.6 Common Error in Selection Statement
Common Error 1: Forgetting Necessary Braces

46 4.6 Common Error in Selection Statement
Common Error 2: Wrong Semicolon at the if Line Does not belongs to if statement

47 4.6 Common Error in Selection Statement
Common Error 3: Redundant Testing of Boolean Values

48 4.6 Common Error in Selection Statement
Common Error 4: Using = instead of == No compilation error. It assigns true to even, so that even is always true.

49 4.6 Common Error in Selection Statement
Common Error 5: Dangling else Ambiguity Nothing is printed. To force the else 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\n"); } else printf("B\n"); This statement prints B.

50 Check Point 3.11 Which of the following statements are equivalent? Which ones are correctly indented? a, c, and d are the same. (B) and (C) are correctly indented.

51 Check Point 3.12 Rewrite the following statement using a Boolean expression: if (count % 10 == 0) newLine = true; else newLine = false; 12. newLine = (count % 10 == 0);

52 Check Point 3.13 Are the following statements correct? Which one is better? 13. Both are correct. (b) is better.

53 Check Point 3.14 What is the output of the following code if number is 14, 15, and 30? number value Output for (a) Output for (b) 14 14 is even 15 15 is multiple of 5 30 30 is even 30 is multiple of 5

54 Check Point 17. Yes.

55 Program output: (bold – user input)
Exercise: Simple calculator (switch) Prompt the user for two values and an operators (+, -, *, /). Calculate the answer based on the operator. Program output: (bold – user input) Value 1: 10.5 Value 2: 5.1 Operator: + Result: = 15.6

56

57 4.7 switch Statement A switch statement
executes statements based on the value of a variable or an expression. The switch statement evaluates an expression, then attempts to match the result to one of several possible cases Each case contains a value and a list of statements The flow of control transfers to statement associated with the first value that matches

58 4.7 switch Statement Syntax

59 4.7 switch Statement break statement:
Often a break statement is used as the last statement in each case's statement list A break statement causes control to transfer to the end of the switch statement If a break statement is not used, the flow of control will continue into the next case Sometimes this can be appropriate, but usually we want to execute only the statements associated with one case

60 4.7 switch Statement default case statement: optional
has no associated value simply uses the reserved word default can be positioned anywhere, usually it is placed at the end default case is present control will transfer to it if no other case value matches no default case, and no other value matches, control falls through to the statement after the switch

61 4.7 switch Statement switch statement rules:
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. The case statements are executed in sequential order.

62 4.7 switch Statement 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 is true. The order of the cases (including the default case) does not matter. However, it is a good programming style to follow the logical sequence of the cases and place the default case at the end.

63 4.7 switch Statement Example 1:

64 4.7 switch Statement Example 1:

65 4.7 switch Statement Example 2: SwitchDemo.java
Try remove all break statement. Remove default case.

66 Check Point 3.29 What data types are required for a switch variable? Switch variables must be of char, byte, short, or int data types. If the keyword break is not used after a case is processed, what is the next statement to be executed? If a break statement is not used, the next case statement is performed. Can you convert a switch statement to an equivalent if statement, or vice versa? You can always convert a switch statement to an equivalent if statement, but not an if statement to a switch statement. What are the advantages of using a switch statement? The use of the switch statement can improve readability of the program in some cases. The compiled code for the switch statement is also more efficient than its corresponding if statement.

67 Check Point 3.30 What is y after the following switch statement is executed? Rewrite the code using the if-else statement. y is 2. x = 3; y = 3; if(x + 3 == 6) y = 1; else y += 1;

68 Check Point 3.31 What is x after the following if-else statement is executed? Use a switch statement to rewrite it and draw the flowchart for the new switch statement. 31. x is 17 switch (a) { case 1: x += 5; break; case 2: x += 10; break; case 3: x += 16; break; case 4: x += 34; }

69 Check Point 3.31 What is x after the following if-else statement is executed? Use a switch statement to rewrite it and draw the flowchart for the new switch statement.

70 Check Point 3.32 Write a switch statement that assigns a String variable dayName with Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, if day is 0, 1, 2, 3, 4, 5, 6, accordingly. switch (day) { case 0: dayName = "Sunday"; break; case 1: dayName = "Monday"; break; case 2: dayName = "Tuesday"; break; case 3: dayName = "Wednesday"; break; case 4: dayName = "Thurday"; break; case 5: dayName = "Friday"; break; case 6: dayName = "Saturday"; break; }

71

72 4.9 Conditional operator conditional operator
evaluates a boolean condition that determines which of two other expressions is evaluated The result of the chosen expression is the result of the entire conditional operator Syntax is: condition ? expression1 : expression2 If the condition is TRUE, expression1 is evaluated; if it is FALSE, expression2 is evaluated

73 4.9 Conditional operator conditional operator
The conditional operator is similar to an if-else statement, except that it forms an expression that returns a value Example: larger = ((num1 > num2) ? num1 : num2); If num1 is greater than num2, then num1 is assigned to larger; otherwise, num2 is assigned to larger The conditional operator is ternary because it requires three operands

74 4.9 Conditional operator conditional operator if (x > 0) y = 1;
else y = -1; equivalent y = (x > 0) ? 1 : -1;

75 4.9 Conditional operator Example: ConditionalOperator.c

76 Check Point 3.33 Suppose that, when you run the following program, you enter input from the console. What is the output? 33. Sorted

77 Check Point 3.34 Rewrite the following if statements using the conditional operator. (A) ticketPrice = (ages >= 16) ? 20 : 10;

78 Check Point 3.35 Rewrite the following conditional expressions using if-else statements. a. score = (x > 10) ? 3 * scale : 4 * scale; (A) if (x > 10) score = 3 * scale; else score = 4 * scale;

79 Check Point 3.35 Rewrite the following conditional expressions using if-else statements. b. tax = (income > 10000) ? income * 0.2 : income * ; (B) if (income > 10000) tax = income * 0.2; else tax = income * ;


Download ppt "CHAPTER 4 Selection CSEG1003 Introduction to Computing"

Similar presentations


Ads by Google