1 / 64

Microsoft Visual Basic 2010: Reloaded Fourth Edition

Microsoft Visual Basic 2010: Reloaded Fourth Edition. Chapter Four Making Decisions in a Program. Structured Programming Algorithms Pseudocode Control Structures If...Then Selection Statement If...Then...Else Selection Statement and Conditional If Expressions

deandra
Download Presentation

Microsoft Visual Basic 2010: Reloaded Fourth Edition

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. Microsoft Visual Basic 2010: ReloadedFourth Edition Chapter Four Making Decisions in a Program

  2. 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 Overview

  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

  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

  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 dayat the office.

  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. • Programcontrol refers to the task of orderingan application’s statements correctly.

  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 executablestatements—the actions performed when the corresponding Visual Basic application is run.

  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

  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.

  10. Sequence Structure • The sequencestructure 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. • Transferof control occurs when an executed statement does not directly follow the previously executed statement in the written application.

  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 keywordsTrue and False. • Refer to a condition as a Boolean expression. • Visual Basic provides three types of selectionstructures

  12. Selection Structures • 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 SelectCasestructure performs one of many actions (or sequences of actions), depending on the value of an expression.

  13. Selection Structures • The If...Then structure is called a single alternative selectionstructure 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 SelectCase structure is called a multiple-selectionstructure because it selects among many different actions or sequences of actions.-

  14. Repetition Structures • Visual Basic provides seven types of repetitionstructures for performing a statement or groupof statements repeatedly: • While...EndWhile • DoWhile...Loop • DoUntil...Loop • Do...LoopWhile • Do...LoopUntil • For...Next • ForEach...Next

  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 IfstudentGrade>=60ThendisplayLabel.Text="Passed"EndIf

  16. If...Then Selection Statement • Conditions in If...Then statements can be formed by using the equalityoperators and relationaloperators(also called comparisonoperators), which are summarized in Fig. 7.4. Figure 7.4| Equality and relational operators.

  17. If...Then...Else Selection Statementand Conditional If Expressions • 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: IfstudentGrade >= 60ThendisplayLabel.Text = "Passed"ElsedisplayLabel.Text = "Failed"End If Can also be written using a conditional If expression: displayLabel.Text = If(studentGrade >= 60, "Passed", "Failed")

  18. If...Then...Else Selection Statementand Conditional If Expressions • NestedIf...Then...Elsestatements testfor 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”

  19. Introducing the Wage Calculator Application 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.

  20. 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 CalculateButton.

  21. Constructing the Wage Calculator Application • Pseudocode describing the basic operation of the WageCalculator application. When the user clicks the Calculate Button Retrieve the number of hours worked and hourly wage from the TextBoxes 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

  22. KeywordConstspecifies constant

  23. Condition between keywordsIfandThen Elsebody executes whencondition evaluates toFalse Assignment operator assigns left operand result of adding left and right operands Format result as currency

  24. 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: <>

  25. Figure 4-10: How to use comparison operators in a condition

  26. Comparison Operators (cont’d.) Figure 4-10: How to use comparison operators in a condition (cont’d.)

  27. 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

  28. Comparison Operators (cont'd.) Figure 4-11: Evaluation steps for an expression containing arithmetic and comparison operators

  29. Comparing Numeric Values • Auction House application displays highest and lowest of two bids entered by the user

  30. Comparing Numeric Values (cont'd.) Figure 4-15: Code entered in the Display button’s Click event procedure

  31. Comparing Numeric Values (cont'd.) Figure 4-15: Code entered in the Display button’s Click event procedure (cont’d.)

  32. 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 • ControlChars.NewLine constant: • Advances the insertion point to the next line

  33. Comparing Numeric Values (cont'd.) Figure 4-17: How to concatenate strings

  34. 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

  35. Figure 4-21: Calculate button’s Click event procedure

  36. The ToUpper and ToLower Methods Figure 4-22: How to use the ToUpper and ToLower methods

  37. The ToUpper and ToLower Methods (cont’d.) Figure 4-22: How to use the ToUpper and ToLower methods (cont'd.)

  38. Figure 4-23: Examples of using the ToUpper method in the calcButton Click event procedure (cont’d.)

  39. Logical Operators • Simpleconditions such as count<=10, total>1000, and number<>value use only one condition with one of the operators >, <, >=, <=, = or <>. • Visual Basic provides logicaloperators that can be used to form complex conditions. They are evaluated after arithmetic or comparison operators in an expression • The logical operators are: • And • AndAlso • Or • OrElse • Xor • Not

  40. Figure 4-27: Truth tables for the AndAlso and OrElse logical operators

  41. Logical Operators • Truth tables: used to evaluate logical operators in an expression • Short-circuit evaluation: an evaluation in which the second condition may not be evaluated • AndAlso evaluates to True only when both sub-conditions are True • OrElse evaluates to False only when both sub-conditions are False • AndAlso and OrElse operations do not evaluate the second condition if the first condition is false

  42. Logical Operators • Using AndAlso • To ensure that two conditions are both true in an application, use the logical AndAlso operator as follows: If genderTextBox.Text = "Female"AndAlso age >= 65Then seniorFemales += 1End If • Figure 8.17 illustrates the outcome of using the AndAlso operator with two expressions. Such tables are called truth tables. Figure 8.17| Truth table for the AndAlso operator.

  43. Logical Operators • Using OrElse • To ensure that either or both of two conditions are true,use the OrElse operator. If (semesterAverage >= 90) OrElse (finalExam >= 90)Then MessageBox.Show("Student grade is A", "Student Grade", _MessageBoxButtons.OK, MessageBoxIcon.Information)End If • Figure8.18 provides a truth table for the OrElseoperator. • Note that the AndAlso operator has a higher precedence. Figure 8.18| Truth table for the OrElse operator.

  44. Logical Operators • Short-Circuit Evaluation • The following expression stops immediately if genderTextBox.Text is not equal to "Female“ (genderTextBox.Text = "Female") AndAlso (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, calledshort-circuit evaluation, requires fewer operationsand takes less time. • Visual Basic also provides the And and Or operators, which do not short-circuit.

  45. Logical Operators • Using Xor • The logical exclusive OR (Xor) operator is Trueif and only ifone 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. • Figure8.19 provides a truth table for the Xor operator. Figure 8.19| Truth table for the logical exclusive OR (Xor) operator.

  46. Logical Operators • Using Not • Visual Basic’s Not operator enables you to “reverse” the meaning of a condition. IfNot (grade = value) ThendisplayLabel.Text = "They are not equal!“End If • The parentheses around the condition grade=value improve the readability of the condition. • Figure8.20 provides a truth table for the Not operator. Figure 8.20| Truth table for the Not operator (logical negation).

  47. DentalPayment Application • A CheckBox is a small square that either is blank or contains a check mark ( ). • Open the DentalPayment application (Fig. 8.1). CheckBox controls (unchecked) Figure 8.1|Running the completed Dental Payment application.

  48. Designing the DentalPayment Application When the user clicks the Calculate Button Clear previous output If user has not entered a patient name or has not selected any CheckBoxes Display message in dialog Else Initialize the total to zero If “Cleaning” CheckBox is selected Add cost of a cleaning to the total If “Cavity Filling” CheckBox is selected Add cost of receiving a cavity filling to the total If “X-Ray” CheckBox is selected Add cost of receiving an x-ray to the total Format total to be displayed as currency Display total

More Related