1 / 43

Chapter 4: Part 1

Chapter 4: Part 1. Making Decisions. Section 4.1. The Decision Structure. The decision structure allows a program’s logic to have more than one path of execution. Order of Statement Execution. Thus far, our code has been executed sequentially in a sequence structure

clio
Télécharger la présentation

Chapter 4: Part 1

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 4: Part 1 Making Decisions

  2. Section 4.1 The Decision Structure The decision structure allows a program’s logic to have more than one path of execution.

  3. Order of Statement Execution • Thus far, our code has been executed sequentially in a sequence structure • To write meaningful programs we need multiple paths of execution • Some statements should be executed under certain circumstances in a decision structure • This chapter presents the means to execute statements conditionally • Next chapter presents the means to execute the same statements repeatedly

  4. Recall: Sequential Programming Declare variables & constants Store input as variables End Start Copy variable values to appropriate controls on form (labels, textboxes, etc.) Perform calculations; store results in variables

  5. The Decision Structure • Flowchart of atypical decisionstructure • Evaluate thecondition • Is it cold outside? • Execute or skipover some code • If yes, wear a coat Is it cold outside? True False Wear a coat.

  6. Section 4.2 The If...Then Statement The If...Then statement causes other statements to execute only when an expression is true.

  7. General Format • If the expression is True, execute the statements between If…Then and End If • Otherwise, the statements are skipped If expressionThen (code if TRUE) End If

  8. Relational Operators • Usually a condition is formed using a relational operator • A relational operator determines if a specific relationship exists between two values > Greater than < Less than = Equal to <> Not equal to >= Greater than or equal to <= Less than or equal to

  9. Boolean Expressions • Relational operators are binary – meaning they use two operands, for example: length > width Is length greater than width? distance <= 10 Is distance less than or equal 10? • Relational operators are used in Boolean expressions which yield a true or false result

  10. Putting It All Together If…Then statement examples: If decSales > 50000 Then MessageBox.Show("You've earned a bonus!") End If If decSales > 50000 Then MessageBox.Show("You've earned a bonus!") decCommissionRate = 0.12 intDaysOff = intDaysOff + 1 End If

  11. Rules to Remember • The If and the Then must be on the same line • Only a comment may follow the Then • The End If must be on a separate line • Only a comment may follow the End If • Tutorial 4-1 presents an application that uses the If…Then statement

  12. Programming Style • The code between the If…Then and the End If is indented • Visual Basic does not require this • It is a convention among programmers to aid in the readability of programs • By default, the Visual Studios will automatically do this indentation as you enter your program

  13. Using Relational Operators with Math Operators • Math operators are evaluated before relational operators • intX + intY and intA - intB are evaluated first • Most programmers prefer to use parentheses to clarify the order of operations If intX+ intY> intA- intBThen lblMessage.Text = "It is true!" End If If (intX+ intY) > (intA – intB) Then lblMessage.Text = "It is true!" End If

  14. Using Function Calls with Relational Operators • Either or both relational operator operands may be function calls • The return value of the function call is compared to the value using the relational operator If CInt(txtInput.Text) < 100 Then lblMessage.Text = "It is true!" End If

  15. Using Boolean Variables as Flags • A flag is a Boolean variable that signals when some condition exists in the program • Since a Boolean variable is either True or False, it can be used as the condition of an If…Then statement • Since a Boolean variable already evaluates to True or False, an = operator is not required If blnQuotaMet Then lblMessage.Text = "Sales quota met!" End If

  16. Section 4.3 The If...Then...Else Statement The If...Then...Else statement executes one group of statements if the Boolean expression is true and another group of statements if the Boolean expression is false.

  17. General Format • If the expression is True • execute the statements between If…Then and Else • If the expression is False • execute the statements between Else and End If If expression Then (code if TRUE) Else (code if FALSE) End If

  18. Flowchart and Code Example dblTemperature < 40? True False Display Message Nice weather we’re having! Display Message A little cold, isn’t it? If intTemperature < 40 Then MessageBox.Show(“A little cold, isn’t it?”) Else MessageBox.Show(“Nice weather we’re having!”) End If

  19. Two Mutually Exclusive Choices • The If…Then…Else has two choices • The condition will either be True or False • So either the Then clause or Else clause will be executed • These are two mutually exclusive choices • Tutorial 4-2 contains an example of the If…Then…Else construct

  20. Section 4.4 The If...Then...ElseIf Statement The If...Then...ElseIf statement is like a chain of If...Then...Else statements. They perform their tests, one after the other, until one of them is found to be true.

  21. Multiple Possible Choices • The If…Then…ElseIf statement allows for an entire series of possible choices • In pseudocode: If it is very cold Then Wear a coat Elseif it is chilly Wear a light jacket Elseif it is windy Wear a windbreaker Elseif it is hot Wear no jacket

  22. Multiple Possible Choices • Each of the series of conditions in an If…Then…ElseIf is tested in sequence • When a condition is true, the remaining conditions are ignored • The order of the conditions is vital • Wrong order can result in wrong decision - called a logic error • What if it’s chilly and windy? • If windy is tested before chilly, you’d go out with a windbreaker when you need a jacket

  23. General Format • This construction is like a chain of If...Then...Else statements • The Else part of one statement is linked to the If part of another If expression Then (code if TRUE) ElseIfexpression Then (code if TRUE) ElseIfexpression Then (code if TRUE) (can have more ElseIf statements if wanted) Else (code if ALL Ifs were FALSE) End If

  24. Flowchart Very cold? True Wear a heavy jacket False True Chilly? Wear a light jacket False True Windy? Wear a windbreaker False True Hot? Wear no jacket False

  25. Example of ElseIf Usage • Does the order of these conditions matter? • What happens if we reverse the order? If decAvg < 60 Then lblGrade.Text = "F" ElseIfdecAvg < 70 Then lblGrade.Text = "D" ElseIfdecAvg < 80 Then lblGrade.Text = "C" ElseIfdecAvg < 90 Then lblGrade.Text = "B" ElseIfdecAvg <= 100 Then lblGrade.Text = "A" End If

  26. Using Only If…Then Statements • Does this code function correctly? • What is assigned to lblGrade for a 65 average? 75? If decAvg < 60 Then lblGrade.Text = "F" End If If decAvg < 70 Then lblGrade.Text = "D" End If If decAvg < 80 Then lblGrade.Text = "C" End If If decAvg < 90 Then lblGrade.Text = "B" End If If decAvg <= 100 Then lblGrade.Text = "A" End If

  27. Using a Trailing Else • A sequence of ElseIf statements may end with a plain Else, called a trailing Else • If none of the conditions are True, the trailing Else statement(s) will be executed • The trailing Else catches any value that falls through the cracks If decAvg < 60 Then lblGrade.Text = "F" ElseIfdecAvg < 70 Then lblGrade.Text = "D" ElseIfdecAvg < 80 Then lblGrade.Text = "C" ElseIfdecAvg < 90 Then lblGrade.Text = "B" ElseIfdecAvg <= 100 Then lblGrade.Text = "A" Else lblGrade.Text = "Error" End If

  28. Section 4.5 Nested If Statements A nested If statement is an If statement in the conditionally executed code of another If statement. (In this section, we use the term If statement to refer to an If . . . Then, If...Then...Else, or If...Then...ElseIf statement.)

  29. If Statements Within If Statements • Any type of statement may be used inside a set of Then, Else, or ElseIf statements of an If • This includes other If statements • If statements within If statements create a more complex decision structure called a Nested If

  30. Nested If Example • Tutorial 4-4 examines an application that uses nested If Statements • In the application, the customer must meet one of the following qualifications: • Earn $30,000 per year or more and have worked in his or her current job for more than two years. • Have worked at his or her current job for more than five years.

  31. Salary > $30,000? True False Years at current job > 5? Years at current job > 2? True False True False Display message The applicant does not qualify. Display message The applicant qualifies. Display message The applicant does not qualify. Display message The applicant qualifies. Flowchart of Nested If Statements

  32. Examining the Nested If Statement If decSalary> 30000 Then If intYearsOnJob > 2 Then lblMessage.Text = "Qualifies!" Else lblMessage.Text = "Does not qualify." End If Else If intYearsOnJob > 5 Then lblMessage.Text = "Qualifies!" Else lblMessage.Text = "Does not qualify." End If End If

  33. Section 4.9 The Select Case Statement In a Select Case statement, one of several possible actions is taken, depending on the value of an expression.

  34. The Select Case Statement • Similar to If…Then…ElseIf • Performs a series of tests • Conditionally executes the first true condition • Select Caseis different in that: • A single test expression may be evaluated • The test expression is listed once • The possible values of the expression are then listed with their conditional statements • Case Elsemay be included and executed if none of the values match the expression

  35. Select Case General Format Select Case TestExpression [Case ExpressionList [one or more statements]] [Case ExpressionList [one or more statements]] ' Case statements may be repeated ' as many times as necessary. [Case Else [one or more statements]] End Select

  36. Select Case Flowchart Example Test Expression Value 1 Value 2 Value 3 Default/Else Operation 1 Operation 2 Operation 3 Operation 4

  37. Select CasePseudocode Example Select Case (From Input) Case 1 Display “Day 1 is Monday.” Case 2 Display “Day 2 is Tuesday.” Case 3 Display “Day 3 is Wednesday.” Case 4 Display “Day 4 is Thursday.” Case 5 Display “Day 5 is Friday.” Case 6 Display “Day 6 is Saturday.” Case 7 Display “Day 7 is Sunday.” Case Else Display “That value is invalid.” End Select

  38. Select Case Statement Example Select Case CInt(txtDayNumber.Text) Case 1 MessageBox.Show("Day 1 is Monday.") Case 2 MessageBox.Show("Day 2 is Tuesday.") Case 3 MessageBox.Show("Day 3 is Wednesday.") Case 4 MessageBox.Show("Day 4 is Thursday.") Case 5 MessageBox.Show("Day 5 is Friday.") Case 6 MessageBox.Show("Day 6 is Saturday.") Case 7 MessageBox.Show("Day 7 is Sunday.") Case Else MessageBox.Show("That value is invalid.") End Select

  39. More about the Expression List: Multiple Expressions • The Case statement’s expression list can contain multiple expressions, separated by commas Select Case intNumber Case 1, 3, 5, 7, 9 strStatus = "Odd" Case 2, 4, 6, 8, 10 strStatus = "Even" Case Else strStatus = "Out of Range" End Select

  40. More about the Expression List: String Values • The Case statement can test string values Select Case strAnimal Case "Dogs", "Cats" MessageBox.Show("House Pets") Case "Cows", "Pigs", "Goats" MessageBox.Show("Farm Animals") Case "Lions", "Tigers", "Bears" MessageBox.Show("Oh My!") End Select

  41. More about the Expression List:Relational Operators • You can use relational operators in the Case statement • The Is keyword represents the test expression in the relational comparison Select Case decTemperature Case Is <= 75 blnTooCold = True Case Is >= 100 blnTooHot = True Case Else blnJustRight = True End Select

  42. More about the Expression List:Ranges of Values • You can determine whether the test expression falls within a range of values • Requires the To keyword • Smaller number on the left • Larger number on the right • Numbers on each side are included in the range Select Case intScore Case Is >= 90 strGrade = "A" Case 80 To 89 strGrade = "B" Case 70 To 79 strGrade = "C" Case 60 To 69 strGrade = "D" Case 0 To 59 strGrade = "F" Case Else strGrade = "Invalid" End Select

  43. Types of Decisions • If…Then: (do something or do nothing) • If…Then…Else: (do this or do that) • If…Then…ElseIf: (keep testing until you find a TRUE case, only FIRST TRUE used) • Nested Ifs: (follow path of conditions) • Select Case: (find the FIRST matching case)

More Related