Date post: | 21-Dec-2015 |
Category: |
Documents |
View: | 222 times |
Download: | 3 times |
CIS 338: VB Control Structures
Dr. Ralph D. WestfallJanuary, 2006
Computer Programming Words
statements = instructions to computercode blocks lines of statements that work together
execution = running program statementsevaluation = determining values calculating and/or substituting within
statement If A = B Then … substitute actual values for A and B,
then test to see if values are equal
Computer Program Words - 2
flow: order in which statements execute action statements do the actual work control statements determine flow control structure = control statements
that go with each other, plus action statements
'comments are ignored by computer
Another Computer Program Word: Concatenation
“link together in series or chain” (Webster)
& concatenates items regardless of type "Le " & "Dinh" = "Le Dinh" (note space) 1 & 1 = "11"
+ concatenates strings like &, but: 1 + "1" = 2
Common Programming Tasks
handle items differently based on a comparison admission prices based on ages
do very same thing with different items send same letter to 400 students
use same code for different processes saving Word, Excel, or PowerPoint
files to C:\ drive
Selection/Branching - If
always based on a condition (test) condition should evaluate to True or
False A = B A > B AND C < D True
if evaluates to 0, becomes False, e.g., 1-1
one-line If statement If [condition] Then [code] 'don't forget the Then 'code runs only if True
Selection/Branching - If 2
“block” If statement If [condition] Then [line(s) that run when True] End If 'not EndIf (must put space 'between End and If)
Selection/Branching - If 3
If [condition] Then [code that runs if True] Else [code that runs if False] End If
Selection/Branching - If 4
If [condition 1] Then [code runs if 1 True] ElseIf [condition 2] Then [code runs if 2 True] Else 'this/next line optional [code runs if both False] End If 'ElseIf, not Else If
Selection/Branching - If 5
“nested” If statements (indents clarify)
If [condition 1] Then [code runs if 1 True] If [condition 2] Then [code runs if 1 & 2 True] End If 'end of 2nd If End If 'end of 1st If 'example? clothes: gender & income
Selection/Branching - Case
use Select Case for multiple tests makes code easier to read and maintain
starts with Select Case [variable name] 'value can have text or Boolean as well as
numeric values (contra Java)includes multiple variable/action pairs Case [criterion] ' (value or variable) [code to run if variable matches criterion]
may have Case Else (and code) after other pairsends with End Select 'not EndSelect
Selection/Branching - Case 2
Select Case sVegetable 'NG in Java
Case "broccoli" CaloryCount = 50 Case "corn" CaloryCount = 111 Case "peas" CaloryCount = 77 Case Else CaloryCount = 925 End Select
Selection/Branching - Case 3
Case can use other types of selections
Select Case [variable or formula]Case 4, 7, 9 'list
[code to run]Case 11 To 20 ' range
[code to run]Case Is >= 30 'logical comparison
[code to run]
Selection/Branching - Case 4
Comparing to a logical value (like Case Is) Select Case True (or expression) Case nMPG < 10 'evaluated sCategory = "gas guzzler" Case sColor = "blue" sCategory = "dull" Case nTopSpeed > 130 OR sMfg _ = "Ferrari"
sCategory = "sporty" End Select 'Is not used in compare
Selection/Branching - Case 5
usually should have a Case Else tests always stop after a match is found put most common matches near top DON'T let test values overlap like below
Select Case nAge Case Is < 5 strSchool = "preschool" Case Is < 18 strSchool = "highschool" Case Is < 14 'will never run strSchool = "elementary"
Loop Structures
use when need repeated actionsFor…Next know how many repetitions
e.g. process 10 items in an array can use variable for number of
repetitions
Do While or Do Until keep looping until something happens e.g. keep processing to end of file
Loop Structures - For/Next
For nIndex = nStart to nEnd [code to run]
Next nIndex '2nd word is optionalnIndex is an integer variable can access its value in the code in the loop value increments by 1 after each repetition
nStart & nEnd are variables, or integer #s loop ends after loop runs code for last time
(here: last time is when nIndex = nEnd)
Enumeration Loop - For/Each
Dim decItem as Decimal Dim decProdPrice(1) as Decimal decProdPrice(0) = 5.02D 'zero based decProdPrice(1) = 15.99D
For Each decItem in decProdPrice MsgBox(decItem)
Next decItem 'non-integer OK as Eachprocesses all members of an array don't have to know how many members works somewhat like a Do Until
Loop Structures - Do While
Dim nCalc as IntegernCalculated = CInt(Text1.Text)Do While nCalc < 100 nCalculated = Math.Abs(nCalc * 2)Loop 'Abs handles < 0 caseText1.Text = CStr(nCalculated)
keeps going until test evaluates to Falseif test is False at start, loop won't run e.g., if user's initial input is >= 100
Loop Structures – Do… Loop Until
'an initial ReadLine is before loopDo intDataItem = CInt(strInputLine) intTotal += intDataItem strInputLine = strDataInputs.ReadLine() Loop Until strInputLine Is Nothing
keeps going until test evaluates to Trueeven if test is True at start, the block will still run one time
Loops – Do ... Loop While
Dim nTry as Integer Dim nAnswer as Integer = 5 Do nTry = CInt(InputBox("Guess #")) Loop While nTry <> nAnswer
keeps going until test = Falsewill always run code at least one time can also use Do ... Loop Until 'by changing what?
Transfer of Control (“Jumping”)
Subprocedure = block of code that is used often in different parts of a program doesn't return a value often sets value(s) in other parts of
program
Function is similar to a subprocedure but it returns a value to the segment of
code that calls it
Subprocedure (Subroutine)
Sub [name]([By[ ] [args as types]) Handles …
'can include 1+ args after [name][1 or more lines of code to run]
End Sub
can be called (run) in two waysCall [name (args)] 'OR[name (args)] 'the word Call is optional (but I like it)
Subprocedure - 2
Sub CopyRightInfo(ByVal nYear as _ Integer) Handles …
strCRight = VBCRLF & _ "© R. Westfall " & nYear & _ VBCRLF & "All rights reserved"
End Sub
[lines of code] Call CopyRightInfo (2001)
[lines of code] CopyRightInfo(1999)
Scope Considerations
Sub Calc(ByVal nA as Integer, ByVal nB _ as Integer, ByVal nC as Integer)
nC = nA + nB 'nC has local scopeEnd Sub
Call Calc(nNum1, nNum2, nNum3) nTotal = nC 'won't work on local variablenTotal = nNum3 'works OK
Call Calc(nNum1, nNum2, nTotal)'better: don't need nTotal = nNum3 line
Pass by: Reference vs. Value
Call Calc(nNum1, nNum2, nTotal)'passes values "by value" (default)'sub uses copied values of these arguments 'a change of its value in the sub doesn't 'change the value of the argument in the 'calling procedure
Sub Calc(ByRef a as Integer)'changing a in Sub changes value
elsewhere
Reference vs. Value - 2
Sub Calc(ByRef nA as Integer,_ ByVal nB as Integer, ByVal _
nC as Integer)
'nB, nC passed by value'nB and nC values will not be changed
in'calling procedure, even if changed in
sub
Function
Function [fName]([args]) As [type])' can include argument(s) after [name]' argument(s) & function have data type' declarations
[1 or more lines of code to run][fName] = [some value or calculation]'1 line can set value of [function name]
by' having name of function to left of =
End Function
Function - 2
Function SevenX(ByVal i as Integer) As _ Integer 'declare return value
SevenX = i * 7 'function name
'Return i * 7' Return unnecessary if use function name
as' variable to hold calculated return value
End Function
Function - 3
call function by its name in an equation dTotal = CalcTotal(nVisitors,
dPayment)
value is returned in function name function name above is CalcTotal
when you write [function name(args)], the function returns the value it calculates
Function - 4 Function ListPrice(fCost As Single) As Single 'arg type result type
ListPrice = fCost * 1.5 End Function
[lines of code] fPrice(1) = ListPrice(fDealerCost(1)) fPrice(2) = ListPrice(fDealerCost(2) * .95)
'parameter name does not have to be same here 'as in the function
'array variables here, regular variables in 'function (evaluated and substituted)
'can also do calculations within arguments
Subroutine/Function Issues
functions & subroutines used in multiple forms could go into a Class or Modulecan pass objects to subroutines and functions
Sub SetValues(txtName As Object) txtName.Text = "This doesn't work"txtName.Enabled = False
End Sub 'txtName is a TextBox
Subprocedure and Function Advantages
saves typing (or pasting) can use subprocedure or function
name rather than keep repeating same block of code
makes code easier to read and maintain smaller programs code is organized into blocks
Subprocedure and Function Disadvantages
extra work to make code more general may need to pass Boolean variables
to indicate special processing for certain types of itemse.g., to indicate different/extra
processing for different types of customers
extra work may offset the benefits