29
Chapter 4 P 1 Decisions and Conditions Control statements - seqeuncing - selection - repetition (picture later) - abstraction (procedure calls)

Chapter 4 P 1 Decisions and Conditions Control statements - seqeuncing - selection - repetition (picture later) - abstraction (procedure calls)

Embed Size (px)

Citation preview

Chapter 4 P 1

Decisions and Conditions

Control statements - seqeuncing

- selection

- repetition (picture later)

- abstraction (procedure calls)

Chapter 4 P 2

If-statements - a decision is made by the program - a given condition is either True or False

Example If the street is blocked thentake a detour

Endif

Example If English T122 is not full thensign up for English T122

Elsecheck History T122

End If

Chapter 4 P 3

The flowchart for these examples

street is blocked

True

take a detour

False

True branch

False branch

(This is called a null branch)

Chapter 4 P 4

Eng T122is not full

True

sign up forEng T122

False

check on Hist T122

Truebranch

False branch

Chapter 4 P 5

if..then.. - general form

If condition Then statement End If

The statement can be any Visual Basic statement, including another If statement.

Syntax for flowcharts

an individual instruction

decision box

Chapter 4 P 6Example If a student’s GPA is 3.5 or more, write that they are on the Dean’s List.

True

Write “Dean’s List”

GPA >= 3.5False

If sGpa >= 3.5 Thenlbl.HonorMessage.Caption = “Dean’s List”

End If

Chapter 4 P 7if..then..elseIf condition Then

statement 1Else

statement 2 End If

Example A student takes a course on a Pass/Fail basis; a report prints “P” for pass and “F” for fail.

Write “Pass”

Grade = “P”True False

Write “Fail”

If sGrade = “P” Then lblMessage.Caption =“Pass”Else lblMessage.Caption = “Fail”End If

Chapter 4 P 8Note: indentations are required for readability

Definition A boolean expression is a statement which has the value True or False. Example sGPA >= 3.5

sGrade = “P”

Another way to write the statement If sGpa >= 3.5 Then

lbl.HonorMessage.Caption = “Dean’s List”End If

isDim bFlag As BooleanbFlag = (sGpa >= 3.5)If bFlag Then

lbl.HonorMessage.Caption = “Dean’s List”End If

Chapter 4 P 9or

If bFlag = True Thenlbl.HonorMessage.Caption = “Dean’s List”

End If

The statement bFlag = (sGpa >= 3.5)

places the value, either True or False, of the boolean expression sGpa >= 3.5 into the boolean variable bFlag.

The advantage is that a boolean expression can be long and complicated. Using a flag will simplify the code.

Chapter 4 P 10

Terminology A boolean expression or condition is also known as a predicate.

Definition The valus of all predicates and variables in a program is called the state of the program.

Note The state of the progrm is a description of what the program has done at any given moment.

Flowcharting if-statements General If..Then General If..Then..Else

True False True False

Chapter 4 P 11

Note: Advantage of flowcharts - detailDisadvantage of flowcharts - detail

Flowcharts are good for descrbing small pieces of code, not entire programs.

Conditions Relational operators

=<>< = (less than or equal)> = (greater than or equal)< > (not equal)

Example Let iSal_1 = 10000, iSal_2 = 20000, iSal_3 = 30000. (a) iSal_1 = iSal_2 is False(b) iSal_2 < iSal_3 is True

Chapter 4 P 12

Using if statements with option buttons and check boxes - use if-statements for option buttons and check buttons- put the code into the appropriate command button

Example P. 108Example P. 120 Private subCalculate_Click())

Nested if-statements Example P. 108, 109

If iTemp > 32 ThenIf iTemp > 80 Then

lblComment.Caption = “Hot”Else

lblComment.Caption = “Moderate”End If

Else lblComment.Caption = “Freezing”

End If

Chapter 4 P 13Use Elseif for several If-statementsExample P. 109If iTemp <= 32 Then

lblComment.Caption = “Freezing”Elseif iTemp > 80 Then

lblComment.Caption = “Hot”Else

lblComment.Caption = “Moderate”End If

Note Avoid too much nesting. This is cahracterized by “wide”flowcharts.

Chapter 4 P 14Example Find the largest of three numbers, A, B, C.

First flowchart

A < BTrue False

B < C A < CTrue False True False

Write C Write B Write C Write A

If iA < iB ThenIf iB < iC Then

write iCElse

write iBEnd If

Else If iA < iC Then

write iC Else

write iA End If

End If

Chapter 4 P 15

Second flowchart The idea is to declare an extra variable iMax, which can simplify the flowchart considerably

Max = A

Max < BTrue False

Max = B

Max<CTrue

Max = C

iMax = A

If iMax< B TheniMax = B

End If

If iMax < C TheniMax = C

End If

write iMax

In general, avoid wide flowcharts.

Chapter 4 P 16

Comparing stringsASCII code P. 104 - 105

- all symbols, including numbers, are represented as symbols

- strings are compared left to right (alphabetical order)Example “Bill” < “Hillary”

“2” < “A”“A” < “a”

Comparing the text property of text boxes P. 107- values entered in text boxes are compared as strings- their data type is variant

Example Suppose cSalFirst is 20000 and cSalSecond is 1000000. Then cSalFirst > cSalSecond is True

val(cSalFirst) > val(cSalSecond) is False

Chapter 4 P 17

Comparing uppercase and lowercase characters

Example Let sName_1 be “Smith” and sName_2 be “jones”. Then (sName_1 > sName_2) is False because the ASCII valus of “S” is less than the ASCII value of “j”.

Use ucase or lcase to change the words all to compare the uppercase or lowercase value of the words.

Example ucase(sName_1) > ucase(sName_2) is True.

Compound conditionsThe logical operators, in hierarchical order, are not, and, and or. Example (4 >= 5) and (8 = (3 + 5))

(4 >= 5) or (8 = (3 + 5))not (- 4 > 0)

Chapter 4 P 18Hierarchical order of all operators

( )NOT* / AND+ - ORrelational operators

Example Suppose iNum holds the value 1. 0 < iNum and iNum < 2 gives a syntax error!

The operator of highest precedence is AND. The compiler evaluates iNum AND iNum. But iNum is of type integer, so this expression is not well-defined. It should be written

(0 < iNum) and (iNum < 2)which is true.

See handout

Chapter 4 P 19

Control arrays (Fig. 4.7 - 4.9)- list of controls with the same Name- elements of the list are distinguished by some number - syntax

- give the first control a name- give the second control the same name

- a message box will ask if you want a control array

- select Yes- the Caption may be different

- in code, refer to the elements of the control array by name and number

Example P. 113

Chapter 4 P 20Example Message formatterThe option buttons have Caption Red, Green, Blue, and Black. Suppose their names are all optColor. The code would be

If optColor(0).Value = Checked ThenlblMessage.Forecolor = vbRed

Elseif optColor(1).Value = Checked ThenlblMessage.Forecolor = vbGreen

Elseif optColor(2).Value = Checked ThenlblMessage.Forecolor = vbBlue

Else lblMessage.Forecolor = vbBlackEnd If

Finding the highest or lowest value previous

Chapter 4 P 21

Input validation (for numeric data)Checking for correct data typeExample P. 115

If isNumeric (txtQuantity.Text) ThenlblDue.Caption = cPrice * val (txtQuantity)

End If

Checking for the range of values - the programmer checks that the date entered is reasonable

Example Check that the number of hours per week do not exceed 168.

If iHours > 168 Thensome action

Else cPay = iHours * cWageEnd If

Chapter 4 P 22

Message boxes

Definition A message box is a box within which the program displays a message to the user. (Fig. 4.10)

The general form is MsgBox “string” [,buttons/icon][,“caption on title bar”]

(Everything between the square brackets is optional.)The possible buttons/icons are

vbOkOnly vbCritical vbQuestionvbExclamation vbInformation

Example If iHours > 168 Then MsgBox “Please enter a numeric value”, vbOkOnly, “Error”Else cPay = iHours * cWageEnd If

Chapter 4 P 23Note: The exceptional case (the case that generates the error message) should come first, if possible.

Example If not IsNumeric (txtQuantity.Text) Then MsgBox “Please enter a numeric value”, vbOkOnly, “Error”Else lblDue.Caption = cPrice * Val(txtQuantity.Text)End If

This is better than writing what the book writes, which is

If IsNumeric (txtQuantity.Text) Then lblDue.Caption = cPrice * Val(txtQuantity.Text)Else MsgBox “Please enter a numeric value”, vbOkOnly, “Error”End If

Chapter 4 P 24The message string To include long, formatted messages, do something like

formatted string = Format(formatted string, etc.)string = formatted string & “xxxxxxxxxx”MsgBox formatted string, vbOkOnly, name of box

Example Dim stFormattedString as StringDim stMessageString as String

stFormattedString = Format$(iHighValue, “Standard”)stMessageString = “Your value is higher than” & stFormattedStringMsgBox = stMessageString, vbCritical, “Value out of bounds”

Chapter 4 P 25To have a message extending over several lines, use

- line feed - insert a new line- the code is Chr (10)

- carriage return- place the cursor at the beginning of this new line- the code is Chr (13)

Note: Chr is a method which takes an integer and returns the corresponding ASCII character (if any).

Example Dim stNewline as String

stNewLine = Chr(10) & Chr (13)

Place stNewLine into a string when you want a new line in the message box.

Chapter 4 P 26

Note: Chr is a method which takes an integer and returns the corresponding ASCII character, if any

Example lblMessage.Caption = Chr (90) displays Z

Note that Chr (500) is undefined, and causes an error.

Debugging tools The Debug toolbar

- select View- select Toolbar- select Debug

Definition A break is a pause in the execution of the program. Forcing a break Method 1

- write Stop in the code

Chapter 4 P 27Method 2

- set a break using the debugger- set the cursor where you want the break to occur- select Toggle Breakpoint

- remove the break SAME STEPS- remove all breaks

- select Debug- select Remove all breaks

The Immediate Window - select View and then select Immediate WIndow - allows the user to execute a single intruction- done during Break time

- enter code (either type or copy it)- hit Return

Chapter 4 P 28Watch

- examine a variable or expression during programexecution

-two methods for watchesMethod 1The Watch Pane (Fig. 4.15)

- this is set during design time- allows the user to examine values and predicates- select View and Watch Window - type in a variable or expression and select options-look at the window in Break time

Method 2The Instant Watch

- under Code select View - highlight the variable or expression you wish to examine- under Debug select Instant Watch- Break the code (as before)

Chapter 4 P 29

Stepping through code- execute one or more lines of code individually- Step into

- Break the code- under Debug select Step Into