Presentation is loading. Please wait.

Presentation is loading. Please wait.

Decisions with If Statements Chapter 4. 2 Structures Sequence Structure (so far) Each statement executed in sequence w/o branching into other directions.

Similar presentations


Presentation on theme: "Decisions with If Statements Chapter 4. 2 Structures Sequence Structure (so far) Each statement executed in sequence w/o branching into other directions."— Presentation transcript:

1 Decisions with If Statements Chapter 4

2 2 Structures Sequence Structure (so far) Each statement executed in sequence w/o branching into other directions. Example: Const dblRATE As Double = 0.15 Dim dblSubTotal As Double Dim dblDiscount As Double dblSubTotal = val(txtSubtotal.Text) dblDiscount = dblSubTotal * dblRATE lblDiscount.Text = FormatCurrency(dblDiscount)

3 Chapter 43 Structures, cont. Decision Structure Algorithms often need to execute statements only when a particular condition exists. Programmers write code that provides more than one path of execution—based on particular circumstance. Create a decision structure or tree to illustrate the flow.

4 Chapter 44 Logical Expressions Alternative actions based on conditions of the situation. Examples: Billing program causing overdue-payment notice Payroll program to pay overtime Bonus based on annual performance evaluation

5 Chapter 45 Condition, Action if True, Action if False ConditionAction if TrueAction if False I am really, really hungry. Eat at Tucano’s.Don’t eat anything. It is 12:55 p.m. on Tuesday, February 10. Go to BU 271 for your favorite VB class (of course). Continue eating at Tucano’s.

6 Chapter 46 Flowchart Condition to Test Process if Condition is True Process if Condition is False True False

7 Chapter 47 Flowchart Condition to Test Process if Condition is True Process if Condition is False True False Diamond: Yes/no question Rectangle: Process that is conditionally executed

8 Chapter 48 Example Flowchart I am hungry. Drive to Tucano’s Go to comp. lab. True False Eat! Do ISYS 1200 Assignment.

9 Chapter 49 Pizza Flowchart Create flowchart for #1 on p. 257.

10 Chapter 410 Executes one group of statements if the condition is true and another group of statements if the condition is false. If condition Then statementblock1 statementblock1 Else statementblock2 statementblock2 End If Syntax Rules: Start with If Include Then on same line as If End process with End If If…Then…Else Statement Only executed if condition is true Only executed if condition is false

11 Chapter 411 Relational Operators Form Condition A testing expression that evaluates as True or False. Relational operators determines whether a specific relationship exists between two values. (See Tables 4.1 and 4.2). Examples: Const intWEEK40 as Single = 40 Dim sngHours as Single sngHours > intWEEK40 sngHours <= intWEEK40 sngHours <> intWEEK40 SymbolName <Less than <=Less than or equal to >Greater than >=Greater than or equal to =Equal to <>Not equal

12 Chapter 412 Relational Expression Relational operators are binary. Require two operands dblLength > dblWidth intAge <= intMINOR Relational expressions are evaluated as true or false only; they are not assignment statements. If x = y Then Determines if x and y are equal. If both operands are equal, then expression is true.

13 Chapter 413 =, and <> > or < must precede = No space between symbols Examples: X >= Y X <= Y X <>Y

14 Chapter 414 Statement Block Processed if Condition is True Follows “Then” keyword. Completes series of statements until “Else” or “End If” statement, whichever comes first. Const intMINRATE As Integer = 5 Dim intRating As Integer intRating = val(txtValue.Text) If intRating > intMINRATE Then 'condition dblBonus = dblSales * intHIGHRATE 'True process Else dblBonus = dblSales * intLOWRATE End If Processes True statement block code and skips over the Else statement block.

15 Chapter 415 Statement Block Processed if Condition is False Follows the keyword “Else.” Completes series of statements until “End If” statement. Const intMINRATE As Integer = 5 Dim intRating As Integer intRating = val(txtValue.Text) If intRating > intMINRATE Then 'condition dblBonus =dblSales * intHIGHRATE 'True process Else dblBonus = dblSales * intLOWRATE 'False process End If Skips “True” statement block since false and processes statement block after keyword “Else.”

16 Chapter 416 Standard Conventions While many formats work, use the standard convention of indenting statement blocks to enhance readability (see p. 189). If condition Then true process Else false process End If

17 Chapter 417 Multiple Process Lines If condition is true, continues processing all lines between “Then” and “Else.” If condition is false, processes all lines between “Else” and “End If.” If dblSales > 50000 Then blnGetsBonus = True dblCommissionRate = 0.12 intDaysOff = intDaysOff + 1 End If

18 Chapter 418 Relational Operators and Math Operators Can combine within same expression. Math operators performed first. If intAge + intYears = 80 Then lblMessage.Text = “You can retire.” End If If intAge + intYears > 30+25 Then lblMessage.Text = “You get a raise.” End If

19 Chapter 419 Val () Function If Val(txtInput.Text) > 100 Then intBonus = 1000 End If Intrinsic Val function gets numeric value of text box Text property. The returned value is compared to 100. If the returned value is > 100, the assignment statement executes.

20 Chapter 420 Checkpoint Do exercises on pp. 191-192

21 Chapter 421 Checkpoint (p. 195) X = 0 If x < 1 Then y = 99 Else y = 0 End If X = 100 If x <=1 Then y = 99 Else y = 0 End If Expression is true Y = 99 Expression is false Y = 0

22 Chapter 422 Practice Exercise w/ Event Procedure Get revenue and cost from a user. If the revenue is greater than the cost, calculate the profit and display it in a label with a string of text. Otherwise, calculate the loss and display the loss amount with a description in the label.

23 Chapter 423 Practice Solution Dim dblRevenue as Currency‘dim other vars also dblRevenue = val(txtRevenue.Text) dblCost = val(txtCost.Text) If dblRevenue > dblCost Then dblProfit = dblRevenue – dblCost lblResult.Text = "The company had _ a profit of " & Profit & "." Else dblLoss = dblCost – dblRevenue lblResult.Text = "The company had _ a loss of " & Loss & ".“ End If

24 Chapter 424 Practice Examples Tutorial 4-2 (pp. 193-195) Programming Challenge 1 (p. 258)

25 Chapter 425 Boolean Variable (p. 118 & pp. 190-191) Stores True or False only. Stores results of logical expression Uses Boolean contents to complete decision process in If…Then…Else block Programmers use Booleans to test conditions or set flags. A flag is a Boolean variable that signals when some condition exists.

26 Chapter 426 Boolean Example When flag is false, the condition does not exist. When flag is true, the condition exists. Note: You do not need to use = True to compare the variable to true.

27 Chapter 427 Compound Conditions Using Logical Operators (pp. 206-211) Evaluates multiple conditions. Uses logical operators to connect 2 or more relational expressions into one expression. And Or Xor Not

28 Chapter 428 And Operator Connects 2 expressions. Requires that both expressions evaluate to true. Identify job candidates with > 5 years AND knows at least 3 programming languages If intYears > 5 And intLang >=3 Then If BOTH are true, follow THEN statement. If Years = 5 and Language = 3, follow ELSE statement.

29 Chapter 429 And Truth Table Job Candidates Experience and Language Both conditions must be true to evaluate as True. Test 1 (over 5 years experience) TrueFalse Test 2 Languages 3+ True False

30 Chapter 430 Create And Example Create the following: Experience (label caption) txtExperience (empty text box) Languages (label caption) txtLanguages (empty text box) Check Qualifications (button)

31 Chapter 431 And Logical Operator Example Compare variable value to constant value using relational operator >. Use parentheses around each comparison (not required by assists with readability). Type And logical operator to require that both relational expressions (conditions) are met. Compare variable value to constant value using relational operator >=. Run with 5 & 3 (both conditions not met). Run with 6 & 3 (both conditions met).

32 Chapter 432 Boolean Example Declare Boolean variable. Sets Boolean flag to true if both conditions are met. If trigger is true, do something.

33 Chapter 433 Or Operator Combines 2 expressions. Requires that only one expression is true— doesn’t matter which expression is true. Checks condition to left of Or operator. If that condition is true, the whole expression is evaluated as true. The program does not check the expression on the right side of the Or operator (to avoid wasting CPU time to check 2 nd condition). If condition on left side of Or operator is false, program must check 2 nd condition.

34 Chapter 434 Or Truth Table At least one of the expressions must be true; doesn’t matter which one. Test 1 (over 5 years) TrueFalse Test 2 (3+ languages) True FalseTrueFalse

35 Chapter 435 Or Example If Temp 100 Then lblResult.Text = “Warning” End If Doesn’t matter if temp is 19 or 101—either one is true and will produce warning.

36 Chapter 436 Or Example Change And to Or Run with 6 and 1 6 is > than 5 Program does not even check 2 nd condition Run with 4 and 3 4 is not > 5 (false condition) Program evaluates 2 nd condition 3 >= 3 (true) Thus: entire expression is true

37 Chapter 437 Xor Operator Exclusive Or Creates an expression that is true when one (not both) of the subexpressions is true. If intYears > 5 Xor intNumJobs > 3 intYears = 6; intNumJobs = 3True intYears = 5; intNumJobs = 4True intYears = 6; intNumJobs = 4False

38 Chapter 438 Xor Truth Table ONLY one condition must be true; doesn’t matter which one; if both conditions are true, the entire expression is false Test 1 (over 5 years) TrueFalse Test 2 (3+ languages) TrueFalseTrue FalseTrueFalse

39 Chapter 439 Not Truth Table Opposite Reverses the logical value of an expression: makes a true expression false and a false expression true. Test 1 (only 1) TrueFalse True

40 Chapter 440 Not Example Reverses the truth If Not Age >= 21 Then lblNote.Text = "You are underage _ and can’t buy alcoholic beverages. _ Drink Wild Cherry Pepsi!" Else lblNote.Text = "You are legal. Drink _ whatever you want—in moderation." End If

41 Chapter 441 Business Computer Proficiency Students must earn 80% on each test. If Not dblScore >= dblPROFICIENT Then lblOutput.Text = “Take the test again.” Else lblOutput.Text = “Congratulations!” End If If dblScore < dblPROFICIENT Then lblOutput.Text = “Take the test again.” Else lblOutput.Text = “Congratulations!” End If Same results; note the difference in relational operators.

42 Chapter 442 Input Validation (p. 235) Checking to verify that appropriate values have been entered in a text box. Data entered. Data is numeric. Specific value is entered. Check range of values. Positive value entered (instead of negative). Necessary before performing calculations to avoid run-time errors.

43 Chapter 443 Validate for No Input (p. 213) Make sure text box is not empty upon click command button. Does not detect string of spaces because spaces are characters like “ABC.” If txtYears.Text = "" Then ' display error message ' set focus 'exit the event procedure End If

44 Chapter 444 IsNumeric() Validation (p. 216-217) Evaluates argument in parentheses. Returns True or False based on if argument is valid number. Example: IsNumeric(“12a”) returns false IsNumeric(txtAge.Text) returns true if numeric IsNumeric(txtAge.Text) returns false if not numeric Helps avoid Type Mismatch error at run time. Evaluates user input, can display MessageBox (error message) if not valid number.

45 Chapter 445 IsNumeric() Example If IsNumeric(txtQuantity.Text) Then intQuantity = Val(txtQuantity.Text) dblAmountDue = intQuantity * dblPRICE Else MessageBox("Nonumeric data entered.", _ "Invalid Data“) 'Select text in text box for user to retype. End If Add input validation for numeric to existing program example to test for numeric years & number of languages.

46 Chapter 446 Validate for Correct Range If Val(txtHours.Text) 10 Then 'perform code Else 'display MessageBox error 'select text box to re-enter data Exit Sub‘exits rest of even procedure to avoid ‘performing calculations End If

47 Chapter 447 Validating for Numeric and w/in a Certain Range Use Not IsNumeric as the first condition to determine if the text box contents are not numeric values. Returns True if the text box does not contain numbers. Also used to return error message if text box I empty. (Spaces count as characters though.) Create condition to test for range or to avoid negative value as the second condition. Provide error message, set focus, and exit the event procedure if data entry does not validate. Omit Else statement and continue statements after End If to continue processing.

48 Chapter 448 Selecting Text Contents Upon Receiving Focus (p. 312) Select entire contents of text box upon receiving focus. See Save As dialog box in PowerPoint. Notice that entire contents of the File name text box are selected. White letters on a blue background

49 Chapter 449 Selecting Existing Text Box Contents txtTextBoxName.SelectionStart = 0 Specifies text box name. SelectionStart property holds position of the first selected character. In this case it starts with the first character (0 = first character). txtTextBoxName.SelectionLength Holds the # of characters that are selected. If use txtName.SelectionLength = 5, then 5 characters are selected.

50 Chapter 450 Selecting Text Box Contents txtName.Text.Length Gets the length of the text box content. Applies to other selection statements as well (see string examples on p. 217). txtName.SelectionStart = 0 txtName.SelectionLength = txtName.Text.Length The above two statements identify & select the entire text box contents (see p. 312). txtName.SelectAll The above statement also selects the entire text box contents. Use in a GotFocus event procedure.

51 Chapter 451 Nested If (p. 203) If statement within another If statement. If condition in the main If expression is true, then process an internal If statement. If condition in the main If expression is false, then process a different internal If statement. Examine nested If statement in Tutorial 5 (pp. 203-205)

52 Chapter 452 Nested If If condition Then If nestedcondition Then perform actions Else perform other actions End If Else perform action End If

53 Chapter 453 Example 5% commission on sales under $10,000 10% commission on sales between $10,000 and $20,000 15% commission on sales over $20,000 Create 3 controls txtSales btnCalculate lblCommission What do you need to declare? Write event procedure.

54 Chapter 454 Declarations & Variable Assignment Before continuing to the next slide, think about how to structure the nested If statement. Use a flowchart if necessary.

55 Chapter 455 Nested If

56 Chapter 456 If…Then…ElseIf…Else (p. 196) Another way to do nested If to create decision-making structures. Sequence is critical because the order in which the rules are consulted.

57 Chapter 457 If…ElseIf…Else Example Compare examples 2 lines shorter than nested Ifs (2 slides back) Can only be ONE Else statement here (compared to 2 on nested If) No ElseIf can follow an Else Else must be last set of code; it catches any value that falls through the cracks. Edit program with this approach. Review Tutorial 4-3 on pp. 196-202.

58 Chapter 458 More MessageBox Information Multiple buttons, such as Yes and No Determine action based on which button user clicks. DialogResult.AbortDialogResult.OK DialogResult.RetryDialogResult.Cancel DialogResult.IgnoreDialogResult.Yes DialogResult.No

59 Chapter 459 Determine MessageBox Button Clicked Declare integer variable to store MessageBox button. Dim intResult as Integer intResult = MessageBox.Show(“Do you want to continue?”, _ “Please Confirm”, MessageBoxButtons.YesNo) If intResult = DialogResult.Yes Then ‘Perform an action here ElseIf intResult = DialogResult.No Then ‘Perform a different action here End If


Download ppt "Decisions with If Statements Chapter 4. 2 Structures Sequence Structure (so far) Each statement executed in sequence w/o branching into other directions."

Similar presentations


Ads by Google