CHAPTER 4 Selection CSEG1003 Introduction to Computing

Slides:



Advertisements
Similar presentations
1 Conditional Statement. 2 Conditional Statements Allow different sets of instructions to be executed depending on truth or falsity of a logical condition.
Advertisements

L5:CSC © Dr. Basheer M. Nasef Lecture #5 By Dr. Basheer M. Nasef.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 4: Selections.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 3 Control Statements.
Introduction to Java Programming, 4E Y. Daniel Liang.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 3 Selections.
Aalborg Media Lab 23-Jun-15 Software Design Lecture 6 “Conditionals and Loops”
ECE122 L7: Conditional Statements February 20, 2007 ECE 122 Engineering Problem Solving with Java Lecture 7 Conditional Statements.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Logical Operators and Conditional statements
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.1 Chapter 3 Selections.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 3 Selections.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Control Statements.
Boolean Expressions and If Flow of Control / Conditional Statements The if Statement Logical Operators The else Clause Block statements Nested if statements.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 3 Selections.
CONTROL STATEMENTS Lakhbir Singh(Lect.IT) S.R.S.G.P.C.G. Ludhiana.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 3 Selections.
CONTROL STATEMENTS IF-ELSE, SWITCH- CASE Introduction to Computer Science I - COMP 1005, 1405 Instructor : Behnam Hajian
© Copyright 2013 by Pearson Education, Inc. All Rights Reserved.1 Chapter 3 Selections.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 3 Selections.
Programming in Java (COP 2250) Lecture 11 Chengyong Yang Fall, 2005.
Chapter 3 Selections Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved
Flow of Control Part 1: Selection
Making Decisions Chapter 5.  Thus far we have created classes and performed basic mathematical operations  Consider our ComputeArea.java program to.
Introduction to Control Statements JavaScript – Part 3 George Mason University June 3, 2010.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Selection Statements Selection Switch Conditional.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X1 Chapter 3 Control Statements.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X1 Chapter 3 Control Statements.
Flow of Control Chapter 3. Outline Branching Statements Java Loop Statements Programming with Loops The Type boolean.
Control structures in C by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.1 Chapter 3 Selections.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
Introduction to Control Statements IT108 George Mason University.
Chapter 3 Selections Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved
Lecture 3 Selection Statements
Chapter 3 Selection Statements
Chapter 4 Selections © Copyright 2012 by Pearson Education, Inc. All Rights Reserved.
Group Project (Find your group members)
Chapter 3 Selections Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.
CNG 140 C Programming (Lecture set 3)
Chapter 3 Selections Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved.
Chapter 3 Selections Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.
Chapter 3 Control Statements
COMP 14 Introduction to Programming
Selections Java.
Lecture 3- Decision Structures
Chapter 3 Selections ACKNOWLEDGEMENT: THESE SLIDES ARE ADAPTED FROM SLIDES PROVIDED WITH Introduction to Java Programming, Liang (Pearson 2014)
EGR 2261 Unit 4 Control Structures I: Selection
Boolean Expressions and If
Chapter 3 Control Statements Lecturer: Mrs Rohani Hassan
Chapter 3 Selections Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved
Chapter 5 Control Statements
Chapter 3 Selections Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1.
Chapter 3 Selections Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved
Relational & Logical Operators, if and switch Statements
Chapter 4: Control Structures I (Selection)
© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.
Boolean Expressions to Make Comparisons
Chapter 3 Selections Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.
Comparing Data & the ‘switch’ Statement
Comparing Data & the ‘switch’ Statement
CprE 185: Intro to Problem Solving (using C)
Chapter 3 Selections Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1.
Module 3 Selection Structures 6/25/2019 CSE 1321 Module 3.
Controlling Program Flow
ICS103: Programming in C 4: Selection Structures
Presentation transcript:

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

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

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.1 Comparison Operators (Relational Operator) Six comparison operators:

4.1 Comparison Operators (Relational Operator)

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

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

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

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

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

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.

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

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

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

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

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;

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.

4.3 Operators Precedence & Associativity high low

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

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 3 + 16 > 5 * 7 – 1 3 + 16 > 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

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.

Check Point 3.41 Evaluate the following expressions: 2 * 2 - 3 > 2 && 4 – 2 > 5 false 2 * 2 - 3 > 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.

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

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.

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.

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.

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.

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;

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:

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.

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.

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

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

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;

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

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

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;

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

4.5 Nested If & Multi-way If-Else statement

4.5 Nested If & Multi-way If-Else statement

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.

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.

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

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

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

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

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.

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.

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

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);

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

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

Check Point 17. Yes.

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: 10.5 + 5.1 = 15.6

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

4.7 switch Statement Syntax

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

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

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.

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.

4.7 switch Statement Example 1:

4.7 switch Statement Example 1:

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

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.

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;

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; }

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.

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; }

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

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

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

4.9 Conditional operator Example: ConditionalOperator.c

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

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

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;

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