1 / 51

Chapter 3 DECISION STRUCTURES

Chapter 3 DECISION STRUCTURES. 1. 1. THE if STATEMENT. The if statement allows us to specify the condition under which a statement or block of statements is to be executed. The general form of the if statement is as follows: if (Boolean expression) { statement(s); }. 2. 2.

brandie
Download Presentation

Chapter 3 DECISION STRUCTURES

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 3DECISION STRUCTURES 1 1

  2. THE ifSTATEMENT The if statement allows us to specify the condition under which a statement or block of statements is to be executed. The general form of the if statement is as follows: if (Boolean expression) { statement(s); } 2 2

  3. THE ifSTATEMENT The key word if is followed by a parenthesized Boolean expression, often called the conditional expression. If the conditional expression is true, the statement(s) in the block that follows are executed. The statement(s) in the block are skipped if the conditional expression is false. We say that the block of statements is conditionally executed, because they are only executed when the condition is true. if (Boolean expression) { statement(s); } 3 3

  4. THE ifSTATEMENTUsing Relational Operators to Form Boolean Expressions Frequently, the Boolean expression used as the condition in an if statement is formed using a relational operator. A relational operator tests whether a particular relationship exists between its operands. *** See Table 3-1 of the text 4 4

  5. THE ifSTATEMENTUsing Relational Operators to Form Boolean Expressions 5 5

  6. THE ifSTATEMENT Using Relational Operators to Form Boolean Expressions All of the relational operators are Binary operators, meaning they take two operands. The relational operators have lower precedence than the arithmetic operators *, /, %, +, and –, but higher precedence than the assignment operators (including the combined assignment operators). The relational operators associate from left-to-right. *** See Appendix C of the text 6 6

  7. THE ifSTATEMENT Using Relational Operators to Form Boolean Expressions Problem: Given the values of the variables for each row at the left, fill in the table showing the values of the expressions given. Note: The value of a relational expression is either true or false. 7

  8. THE ifSTATEMENT Example: The statement below specifies that five is to be added to t only if x is greater than zero. if (x > 0) { t += 5; } 8 8

  9. THE ifSTATEMENT The logic of the if statement given could be depicted as follows: if (x > 0) { t += 5; } true x > 0 false t = t + 5 9 9

  10. THE ifSTATEMENT Notice that there is not a semicolon after the parenthesized Boolean expression. Remember that a semicolon marks the end of a statement, not the end of a line. A complete if statement includes a conditionally executed statement or block. if (x > 0) { t += 5; } There should not be a semicolon here! 10 10

  11. THE ifSTATEMENT If you accidentally put a semicolon after the conditional expression, the compiler will think that the conditionally executed statement is the null statement. The null statement is an empty statement that does nothing. if (x > 0); { t += 5; } The semicolon disconnects the statement t += 5 from the if. The statement t += 5 is no longer conditionally executed. Five will always be added to t regardless of the value of x. Putting a semicolon here is a logical error. 11 11

  12. THE ifSTATEMENT Example: The following statement specifies that the message “Error: Invalid weight entered.” is to be displayed on a line on the computer screen only if weight is less than or equal to zero. if (weight <= 0) { System.out.println("Error: Invalid weight entered."); } 12 12

  13. THE ifSTATEMENT Example: The if statement below specifies that if the value stored in the variable rating is equal to the character ‘S’, the actions described below are taken in the order given. if (rating == 'S') { x = i * .15; z –= x; y = z + 10000; } 1. The value of the variable i is to be multiplied by .15 and the result obtained is assigned to the variable x. 2. The value in the variable z is to be reduced by the value in the variable x. 3. 10000 is to be added to the value of the variable z and the resulting value is assigned to the variable y. 13 13

  14. THE ifSTATEMENT It is possible to omit the braces if a single statement is to be executed if the conditional expression is true. 14 14

  15. THE ifSTATEMENT Example: The braces are not necessary in the following if statement: if (age >= 62) { senior = true; } The if statement below is equivalent to the one above. Both specify that senior is assigned the value true, if the variable age contains a value of 62 or more. if (age >= 62) senior = true; 15 15

  16. THE ifSTATEMENT It is recommended that you enclose a single conditionally executed statement in braces. If there are no braces and another statement is inserted between the conditional expression and the conditionally executed statement, the second statement is disconnected from the conditional expression and will execute regardless of the value of conditional expression. 16 16

  17. THE ifSTATEMENT Without the braces, the value of the conditional expression controls only the execution of the statement that immediately follows it. 17 17

  18. THE ifSTATEMENT Example: The conditionally executed statement in the segment below is x = i * .15. The other statements are executed regardless of the value of rating. if (rating == 'S') x = i * .15; z -= x; y = z + 10000; 18 18

  19. THE ifSTATEMENT Remember the indentation is for the human reader. The compiler generally ignores spaces, tabs, and newlines that are not inside quotation marks. 19 19

  20. THE ifSTATEMENT Example: The segments below are equivalent. // segment 1 follows if (rating == 'S') x = i * .15; z -= x; y = z + 10000; // segment 2 follows if (rating == 'S') x = i * .15; z -= x; y = z + 10000; 20 20

  21. THE ifSTATEMENTProgramming Style for ifStatements The programming style for writing if statements is shown below: if (x > 0) { t += 5; } When writing an if statement: Begin the conditionally executed statement or block on the line below the if (Boolean expression). Indent the conditionally executed statement(s) one level from the key word if. 21 21

  22. FLAGS A flag is a boolean variable that signals when some condition exists in a program. When the flag variable has the value false it means the condition does not exist. When the flag variable is true it means the condition exists. 22 22

  23. FLAGS Example: The variable senior might be used to signal that the user is a senior citizen. boolean senior = false; if (age >= 62) { senior = true; } Later in the program we might use the flag variable senior in determining the price of a movie ticket. if (senior) // You could equivalently write if (senior == true) { ticketPrice *= 0.80; } 23 23

  24. THE if/else STATEMENT If we want one set of statements to be executed if a condition is true and another set of statements to be executed if the condition is false, we can use an if/else statement. The general form of an if/else statement is as follows: if (Boolean expression) { statement(s); // if block } else { statement(s); // else block } 24

  25. THE if/else STATEMENT The parenthesized conditional expression following the key word if is evaluated. If the expression evaluates to true, the statement(s) in the if block are executed. If the conditional expression is false, the statement(s) in the else block are executed. After the execution of one or the other of the blocks execution continues with the statement that follows the else block. if (Boolean expression) { statement(s); // if block } else { statement(s); // else block } 25

  26. THE if/else STATEMENT Example: The following statement specifies that as long as divisor is not equal to 0 the value in dividend is divided by the value in divisor and the result of the division is stored in quotient and this value is then displayed in a console window. If however, divisor is equal to 0, the error message “Error: cannot divide by zero.” is displayed. if (divisor != 0) { quotient = dividend / divisor; System.out.println(dividend + " / " + divisor + " is " + quotient); } else { System.out.println("Error: cannot divide by zero."); } 26

  27. THE if/else STATEMENT Programmers must write code to guard against division by zero. Dividing by zero is a logical/runtime error. if (divisor != 0) { quotient = dividend / divisor; System.out.println(dividend + " / " + divisor + " is " + quotient); } else { System.out.println("Error: cannot divide by zero."); } 27

  28. THE if/else STATEMENT The diagram below shows how the previous if/else statement could be depicted in a flowchart. 28

  29. THE if/else STATEMENT Notice that there is not a semicolon after the parenthesized Boolean expression or the key word else in an if/else statement. if (divisor != 0) { quotient = dividend / divisor; System.out.println(dividend + " / " + divisor + " is " + quotient); } else { System.out.println("Error: cannot divide by zero."); } Do not put semicolons here! 29

  30. THE if/else STATEMENT When a single statement is to be conditionally executed the braces can be omitted. Again, this is not recommended. 30

  31. THE if/else STATEMENT Programming Style for if/elseStatements You should adhere to the following style rules for writing if/elsestatements: The else corresponding to an if should be at the same level of indentation as the if. The block that is executed if the conditional expression is true should begin on the line below the conditional expression and the statements should be indented one level from the key word if. The block that is executed if the conditional expression is false should begin on the line below the key word else and the statements in this block should be indented one level from the key word else. 31

  32. THE if/else STATEMENT Pseudocode for a Program to Calculate the Area of a Circle Ask the user to enter the radius of the circle Store the value entered in radius If the radius is greater than 0 Calculate the circle’s area by multiplying the value of π (approx. 3.14159) by the radius squared. Store the resulting value in area Display the area Else Display an error message indicating that the radius is not valid 32

  33. THE if/else STATEMENT *** See the program CircleAreaWInputValid.java on webct 33

  34. Problem: Write a program to calculate and display the gross pay of an hourly employee for one week. For time worked over forty hours the employee is paid at 1 ½ times his/her normal hourly pay rate.

  35. ***See the program CalculateGrossPay.java on webct

  36. NESTED if STATEMENTS There are no restrictions on what statements can be inside the conditionally executed block(s) of if or if/else statements. A conditionally executed block may contain an if or if/else statement. We say that an if or an if/else statement is nested, if it is inside a conditionally executed block of another if or if/else statement. An else is associated with the most recent unmatched if in the same block. Remember, indentation does not matter to the compiler. 36

  37. NESTED if STATEMENTS *** See the program CalculateGrossPayWInputValid1.java on webct 37

  38. THE if/elseifSTATEMENT We can create a multi-way decision structure by constructing a chain of if/else statements. 38

  39. THE if/elseifSTATEMENT The general form of the if/elseif statement is as follows: if (Boolean expression) { statement(s) } else if (Boolean expression) { statement(s) } else if (Boolean expression) // Incl. as many else ifs as needed for the alternatives { statement(s) } else { statement(s) } 39

  40. THE if/elseifSTATEMENT When you chain the if/elses in this way, the second ifis actually in the else portion of the first if/else;the third ifis actually in the else portion of the second if/else statement … 40

  41. THE if/elseifSTATEMENT When this type of statement is executed, the various conditional expressions are evaluated in order, from top to bottom, until the first, if any, that evaluates to true is found. The conditionally executed statement or block that follows the first true expression is executed and then execution continues after the last conditionally executed statement. Execution will only get to a particular conditional expression, if all the previous conditional expressions are false. 41

  42. THE if/elseifSTATEMENT The trailing else is optional, it can be used to specify what is to be done if none of the conditional expressions are true. 42

  43. THE if/elseifSTATEMENT We use a special indentation style to encode a multi-way decision. Notice that in this case we are not lining up an else with its associated if. We are doing this to visually convey that we have a multi-way decision not a decision between two alternatives. 43

  44. THE if/elseifSTATEMENT Example: Suppose we wanted to create a program to assign a letter grade corresponding to a numeric grade entered by the user, assuming that the numeric grade entered is a whole number and letter grades are assigned based on the following scale: 90  numeric grades  100  letter grade of A 80  numeric grades  90  letter grade of B 70  numeric grades  80  letter grade of C 60  numeric grades  70  letter grade of D 0  numeric grades  60  letter grade of F Grades outside these ranges are not valid. 44

  45. THE if/elseifSTATEMENT The following is a pseudocode algorithm for solving the problem: Set valid grade to true Ask the user for the numeric grade Store the entered value in grade The pseudocode is continued on the next slide 45

  46. THE if/elseifSTATEMENT If grade > 100 Set valid grade to false Else if grade >= 90 Set letter grade to A Else if grade >= 80 Set letter grade to B Else if grade >= 70 Set letter grade to C Else if grade >= 60 Set letter grade to D Else if grade >= 0 Set letter grade to F Else Set valid grade to false If valid grade is true Display the letter grade Else Display an error message 46

  47. THE if/elseifSTATEMENT ***See the program AssignGradesA.java on webct The first if statement filters out all the grades greater than 100. The second if statement executes only if the first test is false; when the second if statement executes, the value of grade is 100 or less. The second if statement filters out all the grades 90 through 100 inclusive. The third if statement executes only if the first two tests are false; when the third if statement executes, the value of grade is less than 90… 47

  48. THE if/elseifSTATEMENT The ordering of the decisions in AssignGradesA.java is significant. Let's look at another program that is similar. ***See the program AssignGradesB.java on webct 48

  49. THE if/elseifSTATEMENT AssignGradesB.java is logically incorrect. Grades in the 90's, 80's, and 70's are greater than 60, so the decision if (grade >= 60) is true for all of these grades and letterGrade is assigned the value 'D'. The decisions that follow are in the else clause of if (grade >= 60), so these are not executed for any grade of 60 or above. 49

  50. THE if/elseifSTATEMENT Let's look at yet another program that is similar. ***See the program AssignGradesC.java on webct 50

More Related