selection structure

57
Tutorial 4 1 Selection Structure Use to make a decision or comparison and then, based on the result of that decision or comparison, to select one of two paths The condition must result in either a true (yes) or false (no) answer If the condition is true, the program performs one set of tasks. If the condition is false, there may or may not be a different set of tasks to perform

Upload: doris-barber

Post on 31-Dec-2015

27 views

Category:

Documents


0 download

DESCRIPTION

Selection Structure. Use to make a decision or comparison and then, based on the result of that decision or comparison, to select one of two paths The condition must result in either a true (yes) or false (no) answer - PowerPoint PPT Presentation

TRANSCRIPT

Tutorial 4 1

Selection StructureUse to make a decision or comparison and then, based on the result of that decision or comparison, to select one of two paths

The condition must result in either a true (yes) or false (no) answer

If the condition is true, the program performs one set of tasks. If the condition is false, there may or may not be a different set of tasks to perform

Tutorial 4 2

Flowchart Symbols

start/stop oval

process rectangle

input/output parallelogram

selection/repetition diamond

symbols are connected by flowlines

Tutorial 4 3

Selection Structure Flowcharts

T

F

TF

Tutorial 4 4

Selection Structure PseudocodeIf condition is true Then

perform these tasks

End If

Perform these tasks

whether condition is true

or false

If condition is true then

perform these tasks

Else

perform these tasks

End If

Perform these tasks

whether condition is true

or false

Tutorial 4 5

If..Then…Else Statement

If condition Then

[instructions when the condition is true]

[Else

[instructions when the condition is false]]

End If

Tutorial 4 6

Relational Operators=

>

>=

<

<=

<>

Equal to

Greater than

Greater than or equal to

Less than

Less than or equal to

Not equal toThese operators are evaluated from left to right, and are evaluated after any mathematical operators

Tutorial 4 7

Expressions Containing Relational Operators

10 + 3 < 5 * 2

5 * 2 is evaluated first, giving 10

10 + 3 is evaluated second, giving 13

13 < 10 is evaluated last, giving false

7 > 3 * 4 / 2

3 * 4 is evaluated first, giving 12

12 / 2 is evaluated second, giving 6

7 > 6 is evaluated last, giving true

All expressions containing a relational operator will result in either a true or false answer only

Tutorial 4 8

Examples of Relational Operators used in the condition

Write a condition that checks if the value stored in the intNum variable is greater than 123

intNum > 123

Write a condition that checks if the value stored in the strName variable is “Mary Smith”

UCase(strName) = “MARY SMITH”

Tutorial 4 9

UCase FunctionSyntax: UCase(string)

In most programming languages, string comparisons are case sensitive--in other words, the letter “A” is not the same as the letter “a”

Returns the uppercase equivalent of string

Can be used on either side of a comparison, but only on the right side of an assignment

Tutorial 4 10

Logical OperatorsNot

And

Or

Reverses the truth value of condition; false becomes true and true becomes false

All conditions connected by the And operator must be true for the compound condition to be true

Only one of the conditions connected by the Or operator needs to be true for the compound condition to be true

These operators are evaluated after any mathematical and relational operators. The order of precedence is Not, And, Or

Tutorial 4 11

Truth Table for the Not Operator

Value of condition Value of Not conditionTrue False

False True

Tutorial 4 12

Truth Table for the And OperatorValue ofcondition1

Value ofcondition2

Value of condition1And condition2

True True True

True False False

False True False

False False False

Tutorial 4 13

Truth Table for the Or OperatorValue ofcondition1

Value ofcondition2

Value of condition1Or condition2

True True True

True False True

False True True

False False False

Tutorial 4 14

Expressions Containing the And Logical Operator

3 > 2 And 6 > 5

3 > 2 is evaluated first, giving true

6 > 5 is evaluated second, giving true

true And true is evaluated last, giving true

10 < 25 And 6 > 5 + 1

5 + 1 is evaluated first, giving 6

10 < 25 is evaluated second, giving true

6 > 6 is evaluated third, giving false

true And false is evaluated last, giving false

Tutorial 4 15

Expression Containing the Or Logical Operator

8 = 4 * 2 Or 7 < 5

4 * 2 is evaluated first, giving 8

8 = 8 is evaluated second, giving true

7 > 5 is evaluated third, giving false

true Or false is evaluated last, giving true

All expressions containing a relational operator will result in either a true or false answer only

Tutorial 4 16

Evaluation of Expressions Containing Logical Operators

If you use the And operator to combine two

conditions, Visual Basic does not evaluate the

second condition if the first condition is false

If you use the Or operator to combine two

conditions, Visual Basic does not evaluate the

second condition if the first condition is true

Tutorial 4 17

Example of Logical Operators used in the condition

To pass a course, a student must have an average test score of at least 75 and an average project score of at least 35. Write the condition using the variables sngTest and sngProj

sngTest >= 75 And sngProj >= 35

Tutorial 4 18

Example of Logical Operators used in the condition

Only people living in the state of Michigan who are over 65 years old receive a discount. Write the condition using the variables strState and intAge

UCase(strState) = “MICHIGAN” And intAge > 65

Tutorial 4 19

Example of Logical Operators used in the condition

Only employees with job codes of 34

and 67 will receive a raise. Write the

condition using the variable intCode

intCode = 34 Or intCode = 67

Tutorial 4 20

Nested Selection Structure

A nested selection structure is one in which

either the true path or the false path

includes yet another selection structure

Any of the statements within either the true

or false path of one selection structure may

be another selection structure

Tutorial 4 21

Nested If in the true pathIf condition1 Then

[instructions when condition1 is true] If condition2 Then

[instructions when both condition1 and condition2 are true]

[Else[instructions when condition1 is true and condition2 is false]]

End IfElse

[instructions when condition1 is false]]End If

Tutorial 4 22

Nested If in the false pathIf condition1 Then

[instructions when condition1 is true]Else

If condition2 Then

[instructions when condition1 is false and condition2 is true]

[Else[instructions when both condition1 and condition2 are false]]

End IfEnd If

Tutorial 4 23

Nested If Example 1

Write a selection structure that assigns a sales tax rate to the sngTax variable. The tax rate is determined by the state code stored in the intCode variable. Codes of 1 and 3 represent a 4% rate; a code of 2 represents a 5% rate. All other codes represent a 2% rate

Tutorial 4 24

Nested If Example 1

If intCode = 1 Or intCode = 3 ThensngTax = .04

ElseIf intCode = 2 Then

sngTax = .05Else

sngTax = .02End If

End If

Tutorial 4 25

Nested If Example 2

Write a selection structure that assigns a bonus to the sngBonus variable. The bonus is determined by the salesperson’s code (intCode) and, in some cases, by the sales amount (sngSales). If the code is 1 and the salesperson sold at least $10,000, then the bonus is $500; otherwise these salespeople receive $200. If the code is 2 and the salesperson sold at least $20,000, then the bonus is $600; otherwise these salespeople receive $550. All others receive $150.

Tutorial 4 26

Nested If Example 2

If intCode = 1 Then If sngSales >= 10000 Then

sngBonus = 500Else

sngBonus = 200End If

ElseIf intCode = 2 Then

If sngSales >= 20000 ThensngBonus = 600

ElsesngBonus = 550

ElsesngBonus = 150

End IfEnd If

Tutorial 4 27

Nested If Example 2

If intCode = 1 And sngSales >= 10000 Then sngBonus = 500Else

If intCode = 1 And sngSales < 10000 ThensngBonus = 200

ElseIf intCode = 2 And sngSales >= 20000 Then

sngBonus = 600Else

If intCode = 2 And sngSales < 20000 ThensngBonus = 550

ElsesngBonus = 150

End IfEnd If

End IfEnd If

Tutorial 4 28

Case Form of the Selection Structure

Referred to as the extended selection structure

Easier than the nested If to write and understand

Typically used when a selection structure has several paths from which to choose

Tutorial 4 29

Select Case StatementSelect Case testexpression

[Case expressionlist1

[instructions for the first Case]]

[Case expressionlist2

[instructions for the second Case]]

[Case expressionlistn

[instructions for the nth Case]]

[Case Else

[instructions for when the

testexpression does not match any of the expressionlists]]

End Select

Tutorial 4 30

To and Is Keywords

Use the To keyword to specify a range of values when you know both the minimum and maximum values

Use the Is keyword to specify a range of values when you know only one value, either the minimum or the maximum

Tutorial 4 31

Select Case Example 1

Write a selection structure that assigns a sales tax rate to the sngTax variable. The tax rate is determined by the state code stored in the intCode variable. Codes of 1 and 3 represent a 4% rate; a code of 2 represents a 5% rate. All other codes represent a 2% rate.

Tutorial 4 32

Select Case Example 1

Select Case intCodeCase 1, 3

sngTax = .04Case 2

sngTax = .05Case Else

sngTax = .02End Select

Tutorial 4 33

Select Case Example 2

Write a selection structure that assigns a bonus to the sngBonus variable. The bonus is determined by the salesperson’s code (intCode) and, in some cases, by the sales amount (sngSales). If the code is 1 and the salesperson sold at least $10,000, then the bonus is $500; otherwise these salespeople receive $200. If the code is 2 and the salesperson sold at least $20,000, then the bonus is $600; otherwise these salespeople receive $550. All others receive $150.

Tutorial 4 34

Select Case Example 2Select Case intCode

Case 1 Select Case sngSales

Case Is >= 10000sngBonus = 500

Case ElsesngBonus = 200

End SelectCase 2

Select Case sngSalesCase Is >= 20000

sngBonus = 600Case Else

sngBonus = 550End Select

Case ElsesngBonus = 150

End Select

Tutorial 4 35

Select Case Example 2

Select Case TrueCase intCode = 1 And sngSales >= 10000

sngBonus = 500Case intCode = 1 And sngSales < 10000

sngBonus = 200Case intCode = 2 And sngSales >= 20000

sngBonus = 600Case intCode = 2 And sngSales < 20000

sngBonus = 550Case Else

sngBonus = 150End Select

Tutorial 4 36

Option ButtonsUsed in situations where you want to limit the user to only one of two or more related and mutually exclusive choices

Only one in a group can be selected (on) at any one time

When selected, an option button’s Value property contains the Boolean value True; otherwise it contains the Boolean value False

Tutorial 4 37

Option Buttons

Minimum number in an interface is two

Recommended maximum number is seven

Use sentence capitalization for the caption

Assign a unique access key

A default button should be selected when the interface first appears

Tutorial 4 38

Option Buttons

You must use a frame control if you want the interface to contain more than one group of option buttons

Set the TabIndex property of the option buttons in each group so that the user can use the up and down arrow keys to select another button in the group

Tutorial 4 39

Frame Control

Acts as a container for other controls

Used to visually separate controls from one another

The frame and the controls contained within the frame are treated as one unit

You must use a frame control if you want to have more than one group of option buttons

Use sentence capitalization for the optional caption

Tutorial 4 40

Check Box

Used in situations where you want to allow the user to select any number of choices from one or more independent and non-exclusive choices

Any number of check boxes can be selected at any one time

When selected, a check box’s Value property contains the number 1 (vbChecked). When unselected, it contains the number 0 (vbUnchecked)

Tutorial 4 41

Check Box

Use sentence capitalization for the check box’s Caption

Assign a unique access to each check box

You also can use the spacebar to select/deselect a check box that has the focus

Tutorial 4 42

Randomize Statement and the Rnd Function

The Randomize statement initializes

Visual Basic’s random-number

generator

The Rnd function generates random

decimal numbers within the 0 to 1

range, including 0 but not including 1

Tutorial 4 43

Rnd Function

To generate random decimal numbers in a range other than 0 to 1:

(upperbound - lowerbound + 1) * Rnd + lowerbound

To generate random integers:

Int((upperbound - lowerbound + 1) * Rnd + lowerbound)

lowerbound is the lowest integer portion of the range

upperbound is the highest integer portion of the range

Tutorial 4 44

User-defined Sub Procedure

A collection of code that can be invoked from one or more places in a program

Can receive variables or constants, called arguments, that you send (pass) to it

The arguments, if any, are listed inside the parentheses following the procedure’s name

You use the Call statement, whose syntax is Call name [(argumentlist)], to invoke a user-defined sub procedure

Tutorial 4 45

Swapping

To swap the contents of two variables:

Assign the first variable’s value to a temporary variable

Assign the second variable’s value to the first variable

Assign the temporary variable’s value to the second variable

Tutorial 4 46

Local vs Static VariablesA local variable is defined in an event procedure, and it is removed from memory when that event procedure ends

A static variable also is defined in an event procedure, but it retains its value when that event procedure ends

A static variable is a special type of local variable

Tutorial 4 47

LoadPicture FunctionUse to display (clear) a graphic in (from) a form, picture box, or image control

Syntax: LoadPicture([stringexpression])

stringexpression is the location and name of a graphics file, and it is enclosed in quotation marks

LoadPicture() clears the graphic from the control

Tutorial 4 48

MsgBox Function

Displays one of Visual Basic’s predefined dialog boxes, which contains a message, one or more command buttons, and an icon

After displaying the dialog box, the MsgBox function waits for the user to choose a button, then returns a value that indicates which button the user selected

Tutorial 4 49

MsgBox Function

Syntax:MsgBox(prompt[, buttons][, title][,helpfile, context])

prompt is the message you want displayed

buttons is a numeric expression that specifies the number and type of buttons, the icon, the default button, and the modality

title is a string expression displayed in the title bar

Tutorial 4 50

Modality

Application modal

Default modality; user must respond to the dialog box’s message before he or she can continue working in the current application; the user still can access other applications

System modal

All applications are suspended until the user responds to the dialog box’s message

Tutorial 4 51

buttons ArgumentConstant Value Description

vbOKOnly 0 Display OK button only.

vbOKCancel 1 Display OK and Cancel buttons.

vbAbortRetryIgnore 2 Display Abort, Retry, and Ignore buttons.

vbYesNoCancel 3 Display Yes, No, and Cancel buttons.

vbYesNo 4 Display Yes and No buttons.

vbRetryCancel5 Display Retry and Cancel buttons.

vbCritical 16 Display Critical Message icon.

vbQuestion 32 Display Warning Query icon.

vbExclamation48 Display Warning Message icon.

vbInformation 64 Display Information Message icon.

vbDefaultButton1 0 First button is default.

vbDefaultButton2 256 Second button is default.

vbDefaultButton3 512 Third button is default.

vbDefaultButton4 768 Fourth button is default.

vbApplicationModal 0 Application modal; the user must respond to the message box

before continuing work in the current application.

vbSystemModal 4096 System modal; all applications are suspended until the user

responds to the message box.

Tutorial 4 52

Return Values

Constant Value Description

vbOK 1 OK

vbCancel 2 Cancel

vbAbort 3 Abort

vbRetry 4 Retry

vbIgnore 5 Ignore

vbYes 6 Yes

vbNo 7 No

Tutorial 4 53

SelStart Property of a Text Box

Tells Visual Basic where to position the insertion point

Syntax: object.SelStart [ = index]

The first position is position (index) 0

Tutorial 4 54

SelLength Property of a Text Box

Tells Visual Basic how many characters

to select

Syntax: object.SelLength [ = number]

Tutorial 4 55

Len Function

You can use the Len function to

determine the number of characters

contained in a text box

Syntax: Len(textbox.Text)

Tutorial 4 56

Highlighting (selecting) Existing TextUse the following two lines of code:

textbox.SelStart = 0

textbox.SelLength = Len(textbox.Text)

Enter the lines of code in the text box’s GotFocus event, which occurs when an object receives the focus

Tutorial 4 57

Debugging Technique

You can use Visual Basic’s Print method

to verify the contents of the

application’s variables as the

application is running.