Microsoft Visual Basic Reloaded Chapter Four Making Decisions
Microsoft Visual Basic: Reloaded Chapter Four Making Decisions in a Program
2 Overview ■ ■ Structured Programming Algorithms Pseudocode Control Structures If. . . Then Selection Statement If. . . Then. . . Else Selection Statement and Conditional If Expressions ■ Comparison and Logical Operators ■ Checkboxes ■ Random Number Generator 2009 Pearson Education, Inc. All rights reserved.
3 Structured Programming ■ A technique for organizing program control that helps you develop applications that are clear and easier to debug and modify. ■ Thoroughly understand the problem you need to solve first! ■ Be familiar with the building blocks available for you to program ■ Use proven application construction (design) principles 2009 Pearson Education, Inc. All rights reserved.
4 Algorithms ■ Computing problems can be solved by executing a series of actions in a specific order. ■ A procedure for solving a problem, called an algorithm, deals with: the actions to be executed and the order in which these actions are to be executed 2009 Pearson Education, Inc. All rights reserved.
5 Algorithms ■ The following example demonstrates the importance of correctly specifying the order in which the actions are to be executed. Consider the “rise and shine algorithm” followed by one junior executive for getting out of bed and going to work: (1) get out of bed, (2) take off pajamas, (3) take a shower, (4) get dressed, (5) eat breakfast and (6) carpool to work. ■ This routine prepares the executive for a productive day at the office. 2009 Pearson Education, Inc. All rights reserved.
6 Algorithms ■ Suppose that the same steps are performed in a slightly different order: (1) get out of bed, (2) take off pajamas, (3) get dressed, (4) take a shower, (5) eat breakfast, (6) carpool to work. ■ Program control refers to the task of ordering an application’s statements correctly. 2009 Pearson Education, Inc. All rights reserved.
7 Pseudocode ■ Pseudocode is an informal language that helps you formulate algo rithms and think out an application before attempting to write it in a programming language. It is convenient and user friendly Not an actual computer programming language. ■ Pseudocode statements are not executed on computers. ■ Pseudocode normally describes only executable statements—the actions performed when the corresponding Visual Basic application is run. 2009 Pearson Education, Inc. All rights reserved.
8 Pseudocode ■ Example of a pseudocode statement: Assign 0 to the counter ■ The pseudocode statement above can be converted to the following Visual Basic statement: counter = 0 2009 Pearson Education, Inc. All rights reserved.
9 Control Structures ■ Control Structures specify the order which commands are executed in a program. ■ All programs can be written in terms of only three control structures: Sequence structure (1) Selection structure (3) Repetition structure (7) ■ Visual Basic has 11 specific control structure statements ■ All Visual Basic applications are formed by combining as many of each type of control structure as is necessary. 2009 Pearson Education, Inc. All rights reserved.
10 Sequence Structure ■ The sequence structure is built into Visual Basic—unless directed to act otherwise, the computer executes Visual Basic statements sequentially—that is, one after the other in the order in which they appear in the application. ■ Transfer of control occurs when an executed statement does not directly follow the previously executed statement in the written application. 2009 Pearson Education, Inc. All rights reserved.
11 Selection Structures ■ A condition is an expression with a true or false value that is used to make a decision. ■ Conditions are evaluated to determine whether their value is true or false. ■ These values are of data type Boolean Specified in Visual Basic code by using the keywords True and False. ■ Refer to a condition as a Boolean expression. ■ Visual Basic provides three types of selection structures 2009 Pearson Education, Inc. All rights reserved.
12 Selection Structures (3) ■ The If. . . Then selection structure performs (selects) an action (or sequence of actions) based on a condition. If the condition evaluates to True, the actions specified by the If. . . Then structure are executed. If evaluates to False, the actions structure are skipped. ■ The If. . . Then. . . Else selection structure Performs an action (or sequence of actions) if a condition is true and performs a different action (or sequence of actions) if the condition is false. ■ The Select Case structure performs one of many actions (or sequences of actions), depending on the value of an expression. 2009 Pearson Education, Inc. All rights reserved.
13 Selection Structures ■ The If. . . Then structure is called a single alternative selection structure because it selects or ignores a single action (or a sequence of actions). ■ The If. . . Then. . . Else structure is called a dual alternative selection structure because it selects between two different actions (or sequences of actions). ■ The Select Case structure is called a multipleselection structure because it selects among many different actions or sequences of actions. 2009 Pearson Education, Inc. All rights reserved.
14 Repetition Structures (7) ■ Visual Basic provides seven types of repetition structures for performing a statement or group of statements repeatedly: While. . . End While Do While. . . Loop Do Until. . . Loop Do. . . Loop While Do. . . Loop Until For. . . Next For Each. . . Next 2009 Pearson Education, Inc. All rights reserved.
15 If. . . Then Selection Statement ■ A selection statement chooses among alternative courses of action in an application. If student’s grade is greater than or equal to 60 Display “Passed” ■ The preceding pseudocode If statement may be written in Visual Basic as If student. Grade >= 60 Then display. Label. Text = "Passed" End If 2009 Pearson Education, Inc. All rights reserved.
16 If. . . Then Selection Statement ■ Conditions in If. . . Then statements can be formed by using the equality operators and relational operators (also called comparison operators), which are summarized in Fig. 7. 4. Figure 7. 4 | Equality and relational operators. 2009 Pearson Education, Inc. All rights reserved.
If. . . Then. . . Else Selection Statement and Conditional If Expressions 17 ■ The If. . . Then. . . Else selection statement allows you to specify that a different action is to be performed when the condition is true than when the condition is false. If student’s grade is greater than or equal to 60 Display “Passed” Else Display “Failed” Pseudocode converted to Visual Basic: If student. Grade >= 60 Then display. Label. Text = "Passed" Else display. Label. Text = "Failed" End If Can also be written using a conditional If expression: display. Label. Text = If(student. Grade >= 60, "Passed", "Failed") 2009 Pearson Education, Inc. All rights reserved.
If. . . Then. . . Else Selection Statement and Conditional If Expressions 18 ■ Nested If. . . Then. . . Else statements test for multiple conditions by placing If. . . Then. . . Else statements inside other If. . . Then. . . Else statements. If student’s grade is greater than or equal to 90 Display “A” Else If student’s grade is greater than or equal to 80 Display “B” Else If student’s grade is greater than or equal to 70 Display “C” Else If student’s grade is greater than or equal to 60 Display “D” Else Display “F” 2009 Pearson Education, Inc. All rights reserved.
19 2009 Pearson Education, Inc. All rights reserved.
20 2009 Pearson Education, Inc. All rights reserved.
21 Introducing the Wage Calculator Application Requirements A payroll company calculates the gross earnings per week of employees. Employees’ weekly salaries are based on the number of hours they worked and their hourly wages. The application assumes a standard work week of 40 hours. The wages for 40 or fewer hours are calculated by multiplying the employee’s hourly wage by the number of hours worked. Any time worked over 40 hours in a week is considered “overtime” and earns time and a half. The total overtime earned is added to the user’s gross earnings for the regular 40 hours of work to calculate the total earnings for that week. ■ This application calculates earnings from hourly wage and hours worked per week. 2009 Pearson Education, Inc. All rights reserved.
22 Introducing the Wage Calculator Application ■ The employee’s earnings are the sum of the wages for the standard 40 hour work week (40*10) and the overtime pay (5*10*1. 5) (Fig 7. 2). Figure 7. 2 | Calculating wages by clicking the Calculate Button. 2009 Pearson Education, Inc. All rights reserved.
23 Constructing the Wage Calculator Application ■ Pseudocode describing the basic operation of the Wage Calculator application. When the user clicks the Calculate Button Retrieve the number of hours worked and hourly wage from the Text. Boxes If the number of hours worked is less than or equal to 40 hours Gross earnings equals hours worked times hourly wage Else Gross earnings equals 40 times hourly wage plus hours above 40 times wage and a half Display gross earnings 2009 Pearson Education, Inc. All rights reserved.
24 Keyword Const specifies constant 2009 Pearson Education, Inc. All rights reserved.
25 Condition between keywords If and Then Else body executes when condition evaluates to False Assignment operator assigns left operand result of adding left and right operands Format result as currency 2009 Pearson Education, Inc. All rights reserved.
Comparison Operators Comparison operators (or relational operators): Used as part of the condition in an If…Then…Else statement to compare two values Most commonly used comparison operators: Equal to: = Greater than: > Greater than or equal to: >= Less than: < Less than or equal to: <= Not equal to: <> 2009 Pearson Education, Inc. All rights reserved.
2009 Pearson Education, Inc. All rights reserved.
Comparison Operators (cont’d. ) 2009 Pearson Education, Inc. All rights reserved.
Comparison Operators (cont'd. ) Comparison operators: ■ Have no order of precedence ■ Are evaluated from left to right in an expression ■ Are evaluated after any arithmetic operators in the expression All expressions containing comparison operators evaluate to True or False only 2009 Pearson Education, Inc. All rights reserved.
Comparison Operators (cont'd. ) Figure 4 11: Evaluation steps for an expression containing arithmetic and comparison operators 2009 Pearson Education, Inc. All rights reserved.
Comparing Numeric Values ■ Auction House application displays highest and lowest of two bids entered by the user 2009 Pearson Education, Inc. All rights reserved.
Comparing Numeric Values (cont'd. ) Figure 4 15: Code entered in the Display button’s Click event procedure 2009 Pearson Education, Inc. All rights reserved.
Comparing Numeric Values (cont'd. ) Figure 4 15: Code entered in the Display button’s Click event procedure (cont’d. ) 2009 Pearson Education, Inc. All rights reserved.
Comparing Numeric Values (cont'd. ) ■ Block-level variables: declared within a statement block and remain in memory until the procedure ends ■ Block scope: A block scope variable can only be used within the statement block in which it was declared ■ Concatenation operator (&): connects or links two strings together ■ Control. Chars. New. Line constant: ■ Advances the insertion point to the next line 2009 Pearson Education, Inc. All rights reserved.
Comparing Numeric Values (cont'd. ) Figure 4 17: How to concatenate strings 2009 Pearson Education, Inc. All rights reserved.
Comparing Strings ■ Addition and Subtraction Calculator application: displays the sum or difference of two numbers Figure 4 18: Sample run of the Addition and Subtraction Calculator application 2009 Pearson Education, Inc. All rights reserved.
Figure 4 21: Calculate button’s Click event procedure 2009 Pearson Education, Inc. All rights reserved.
The To. Upper and To. Lower Methods 2009 Pearson Education, Inc. All rights reserved.
The To. Upper and To. Lower Methods (cont’d. ) 2009 Pearson Education, Inc. All rights reserved.
Figure 4 23: Examples of using the To. Upper method in the calc. Button Click event procedure (cont’d. ) 2009 Pearson Education, Inc. All rights reserved.
41 Logical Operators ■ Simple conditions such as count <= 10, total > 1000, and number <> value use only one condition with one of the operators >, <, >=, <=, = or <>. ■ Visual Basic provides logical operators that can be used to form complex conditions. They are evaluated after arithmetic or comparison operators in an expression ■ The logical operators are: And. Also Or Or. Else Xor Not 2009 Pearson Education, Inc. All rights reserved.
Figure 4 27: Truth tables for the And. Also and Or. Else logical operators 2009 Pearson Education, Inc. All rights reserved.
Logical Operators ■ Truth tables: used to evaluate logical operators in an expression ■ Short-circuit evaluation: an evaluation in which the secondition may not be evaluated ■ And. Also evaluates to True only when both sub conditions are True ■ Or. Else evaluates to False only when both sub conditions are False ■ And. Also and Or. Else operations do not evaluate the secondition if the first condition is false 2009 Pearson Education, Inc. All rights reserved.
44 Logical Operators ■ Using And. Also To ensure that two conditions are both true in an application, use the logical And. Also operator as follows: If gender. Text. Box. Text = "Female" And. Also age >= 65 Then senior. Females += 1 End If Figure 8. 17 illustrates the outcome of using the And. Also operator with two expressions. Such tables are called truth tables. Figure 8. 17 | Truth table for the And. Also operator. 2009 Pearson Education, Inc. All rights reserved.
45 Logical Operators ■ Using Or. Else To ensure that either or both of two conditions are true, use the Or. Else operator. If (semester. Average >= 90) Or. Else (final. Exam >= 90) Then Message. Box. Show("Student grade is A", "Student Grade", _ Message. Box. Buttons. OK, Message. Box. Icon. Information) End If Figure 8. 18 provides a truth table for the Or. Else operator. Note that the And. Also operator has a higher precedence. Figure 8. 18 | Truth table for the Or. Else operator. 2009 Pearson Education, Inc. All rights reserved.
46 Logical Operators ■ Short Circuit Evaluation The following expression stops immediately if gender. Text. Box. Text is not equal to "Female“ (gender. Text. Box. Text = "Female") And. Also (age >= 65) The evaluation of the second expression is irrelevant; once the first expression is known to be false, the whole expression must be false. This way of evaluating logical expressions, called short-circuit evaluation, requires fewer operations and takes less time. ■ Visual Basic also provides the And and Or operators, which do not short circuit. 2009 Pearson Education, Inc. All rights reserved.
47 Logical Operators ■ Using Xor The logical exclusive OR (Xor) operator is True if and only if one of its operands results in a True value and the other results in a False value. If both operands are True or both are False, the entire condition is false. Figure 8. 19 provides a truth table for the Xor operator. Figure 8. 19 | Truth table for the logical exclusive OR (Xor) operator. 2009 Pearson Education, Inc. All rights reserved.
48 Logical Operators ■ Using Not Visual Basic’s Not operator enables you to “reverse” the meaning of a condition. If Not (grade = value) Then display. Label. Text = "They are not equal!“ End If The parentheses around the condition grade = value improve the readability of the condition. Figure 8. 20 provides a truth table for the Not operator. Figure 8. 20 | Truth table for the Not operator (logical negation). 2009 Pearson Education, Inc. All rights reserved.
49 Dental Payment Application ■ A Check. Box is a small square that either is blank or contains a check mark ( ). ■ Open the Dental Payment application (Fig. 8. 1). Check. Box controls (unchecked) Figure 8. 1 | Running the completed Dental Payment application. 2009 Pearson Education, Inc. All rights reserved.
50 Designing the Dental Payment Application When the user clicks the Calculate Button Clear previous output If user has not entered a patient name or has not selected any Check. Boxes Display message in dialog Else Initialize the total to zero If “Cleaning” Check. Box is selected Add cost of a cleaning to the total If “Cavity Filling” Check. Box is selected Add cost of receiving a cavity filling to the total If “X-Ray” Check. Box is selected Add cost of receiving an x-ray to the total Format total to be displayed as currency Display total 2009 Pearson Education, Inc. All rights reserved.
51 Using Check. Boxes ■ A Check. Box is known as a state button because it can be in the on/off [true/false] state. ■ The text that appears alongside a Check. Box is called the Check. Box label. ■ If the Check. Box is checked, the Checked property contains the Boolean value True; otherwise, it contains False. 2009 Pearson Education, Inc. All rights reserved.
52 2009 Pearson Education, Inc. All rights reserved.
53 Applying these concepts ■ Revise the code so that users must enter a name and select at least one Check. Box before they click the Calculate Button. If they don’t an error dialog will be displayed. ■ Use If Then Else, Or. Else and And. Also to determine if name is entered and at least one Check. Box is selected. ■ clean. Check. Box ■ xray. Check. Box ■ cavity. Check. Box ■ name. Text. Box 2009 Pearson Education, Inc. All rights reserved.
54 2009 Pearson Education, Inc. All rights reserved.
55 2009 Pearson Education, Inc. All rights reserved.
56 2009 Pearson Education, Inc. All rights reserved.
57 Complex Expressions All Checked ■ ■ ■ Checked 1. True = FALSE F AND Checked 2. True = FALSE F AND Checked 3. True = FALSE F FALSE 2009 Pearson Education, Inc. All rights reserved.
58 Complex Expressions – Some Checked ■ ■ ■ Checked 1. False = FALSE AND Checked 2. True = FALSE AND Checked 3. True = FALSE T F F FALSE 2009 Pearson Education, Inc. All rights reserved.
59 Complex Expressions – None Checked ■ ■ ■ Checked 1. False = FALSE AND Checked 2. False = FALSE AND Checked 3. False = FALSE T TRUE 2009 Pearson Education, Inc. All rights reserved.
Summary of Operators Figure 4 31: Listing of arithmetic, concatenation, comparison, and logical operators 2009 Pearson Education, Inc. All rights reserved.
Summary of Operators (cont’d. ) Figure 4 31: Listing of arithmetic, concatenation, comparison, and logical operators (cont’d. ) 2009 Pearson Education, Inc. All rights reserved.
2009 Pearson Education, Inc. All rights reserved.
Generating Random Integers (cont'd. ) 2009 Pearson Education, Inc. All rights reserved.
- Slides: 63