49
1 Ching, Ph.D. • MIS Dept. • California State University, Sacramento Week 15 Week 15 May 10 May 10 Review Review

1 R. Ching, Ph.D. MIS Dept. California State University, Sacramento Week 15 May 10 Review

Embed Size (px)

Citation preview

Page 1: 1 R. Ching, Ph.D. MIS Dept. California State University, Sacramento Week 15 May 10 Review

1

R. Ching, Ph.D. • MIS Dept. • California State University, Sacramento

Week 15Week 15May 10May 10

ReviewReview

Page 2: 1 R. Ching, Ph.D. MIS Dept. California State University, Sacramento Week 15 May 10 Review

2

R. Ching, Ph.D. • MIS Dept. • California State University, Sacramento

Final ExamFinal Exam

• Tuesday, May 17Tuesday, May 17

• 12:45 – 2:4512:45 – 2:45

• BRH-104BRH-104

Page 3: 1 R. Ching, Ph.D. MIS Dept. California State University, Sacramento Week 15 May 10 Review

3

R. Ching, Ph.D. • MIS Dept. • California State University, Sacramento

Data - Variables and ConstantsData - Variables and Constants

• VariableVariable

– Memory locations that hold data that Memory locations that hold data that cancan be changed be changed during project executionduring project execution

– Dim customerName as StringDim customerName as String

• Named ConstantNamed Constant

– Memory locations that hold data that Memory locations that hold data that cannotcannot be be changed during project executionchanged during project execution

– Const salesTaxRate as Decimal = .0775Const salesTaxRate as Decimal = .0775

DeclarationDeclaration Variable nameVariable name Data typeData type

Page 4: 1 R. Ching, Ph.D. MIS Dept. California State University, Sacramento Week 15 May 10 Review

4

R. Ching, Ph.D. • MIS Dept. • California State University, Sacramento

Data Types (p 87 Table 3.1)Data Types (p 87 Table 3.1)

• BooleanBoolean

• Byte (0 to 255)Byte (0 to 255)

• CharChar

• DateDate

• StringString

• DecimalDecimal

• ObjectObject

• Short (-32,768 to 32,767)Short (-32,768 to 32,767)

• Integer (-2,147,483,648 to Integer (-2,147,483,648 to 2,147,483,647)2,147,483,647)

• Long (larger whole numbers)Long (larger whole numbers)

• Single (floating point accuracy to 6 Single (floating point accuracy to 6 digits)digits)

• Double (floating point accuracy to 14 Double (floating point accuracy to 14 digits)digits)

Page 5: 1 R. Ching, Ph.D. MIS Dept. California State University, Sacramento Week 15 May 10 Review

5

R. Ching, Ph.D. • MIS Dept. • California State University, Sacramento

Declaring VariablesDeclaring Variables

• Declared inside a procedure using a Dim statementDeclared inside a procedure using a Dim statement

• Declared outside a procedure using Public, Private or Dim Declared outside a procedure using Public, Private or Dim statementsstatements

• Always declare the variable’s data typeAlways declare the variable’s data type

• May declare several variables with one statementMay declare several variables with one statement

• Use IntelliSense to assist in writing statementsUse IntelliSense to assist in writing statements

Page 6: 1 R. Ching, Ph.D. MIS Dept. California State University, Sacramento Week 15 May 10 Review

6

R. Ching, Ph.D. • MIS Dept. • California State University, Sacramento

Arithmetic OperationsArithmetic Operations

Operator Operation+ Addition– Subtraction* Multiplication/ Division\ Integer Division

Mod Modulus – Remainder of division

^ Exponentiation

Page 7: 1 R. Ching, Ph.D. MIS Dept. California State University, Sacramento Week 15 May 10 Review

7

R. Ching, Ph.D. • MIS Dept. • California State University, Sacramento

Order of OperationsOrder of Operations

• Order of precedence in arithmetic expressions from highest to Order of precedence in arithmetic expressions from highest to lowestlowest

1. Any operation inside parentheses1. Any operation inside parentheses2. Exponentiation2. Exponentiation3. Multiplication and division3. Multiplication and division4. Integer division4. Integer division5. Modulus5. Modulus6. Addition and subtraction6. Addition and subtraction

Page 8: 1 R. Ching, Ph.D. MIS Dept. California State University, Sacramento Week 15 May 10 Review

8

R. Ching, Ph.D. • MIS Dept. • California State University, Sacramento

Mathematical ExamplesMathematical Examples

• Note the use of parentheses to control order of precedenceNote the use of parentheses to control order of precedence

3+4*2 = 11 Multiply then add(3+4)*2 = 14 Parentheses control: add then multiply8/4*2 = 4 Same level, left to right: divide then multiply

Page 9: 1 R. Ching, Ph.D. MIS Dept. California State University, Sacramento Week 15 May 10 Review

9

R. Ching, Ph.D. • MIS Dept. • California State University, Sacramento

Using Calculations in CodeUsing Calculations in Code

• Perform calculations in assignment statementsPerform calculations in assignment statements

• What appears on right side of assignment operator is What appears on right side of assignment operator is assigned to item on left sideassigned to item on left side

• Assignment operatorsAssignment operators

=, +=, -=, *=, /=, \=, &==, +=, -=, *=, /=, \=, &=

Page 10: 1 R. Ching, Ph.D. MIS Dept. California State University, Sacramento Week 15 May 10 Review

10

R. Ching, Ph.D. • MIS Dept. • California State University, Sacramento

Writing General ProceduresWriting General Procedures

• A general procedure is reusable code which can be called A general procedure is reusable code which can be called from multiple proceduresfrom multiple procedures

• Useful for breaking down large sections of code into Useful for breaking down large sections of code into smaller unitssmaller units

• Two typesTwo types– Sub Procedure performs actionsSub Procedure performs actions– Function performs actions AND returns a value (the Function performs actions AND returns a value (the

return valuereturn value))

Page 11: 1 R. Ching, Ph.D. MIS Dept. California State University, Sacramento Week 15 May 10 Review

11

R. Ching, Ph.D. • MIS Dept. • California State University, Sacramento

Creating a New Sub ProcedureCreating a New Sub Procedure

• In the Editor window enclose the lines of code with a set of In the Editor window enclose the lines of code with a set of Private Sub and End Sub statementsPrivate Sub and End Sub statements

• To use the Sub Procedure, call it from another procedureTo use the Sub Procedure, call it from another procedure

• Code in a Sub Procedure cannot be executed unless called Code in a Sub Procedure cannot be executed unless called from another procedurefrom another procedure

Private Sub ProcedureName( )' Statements in the procedure.

End Sub

Page 12: 1 R. Ching, Ph.D. MIS Dept. California State University, Sacramento Week 15 May 10 Review

12

R. Ching, Ph.D. • MIS Dept. • California State University, Sacramento

Passing Arguments to Procedures (page Passing Arguments to Procedures (page 205)205)

• Declare variable as local and pass to any called proceduresDeclare variable as local and pass to any called procedures

• If a sub procedure names an argument, any call to the procedure If a sub procedure names an argument, any call to the procedure must supply the argumentmust supply the argument

• Name of local variable does not need to match name in sub Name of local variable does not need to match name in sub procedure argument listprocedure argument list

• Number of arguments, sequence and data type must matchNumber of arguments, sequence and data type must match

Page 13: 1 R. Ching, Ph.D. MIS Dept. California State University, Sacramento Week 15 May 10 Review

13

R. Ching, Ph.D. • MIS Dept. • California State University, Sacramento

Passing Arguments ByVal or ByRefPassing Arguments ByVal or ByRef

• ByVal (default)ByVal (default)

– Sends a copy, original cannot be alteredSends a copy, original cannot be altered

• ByRefByRef

– Sends a reference to the memory location where the Sends a reference to the memory location where the original is stored and therefore the original can be original is stored and therefore the original can be alteredaltered

• Examples page 206Examples page 206

Page 14: 1 R. Ching, Ph.D. MIS Dept. California State University, Sacramento Week 15 May 10 Review

14

R. Ching, Ph.D. • MIS Dept. • California State University, Sacramento

Sub Procedure ExampleSub Procedure Example

Private Sub SelectColor(incomingColor As Color)With ColorDialog1

.Color = incomingColor

.ShowDialog( )End With

End Sub

Private Sub changeTitleButtonColor_Click( )Dim originalColor As Color

originalColor = titleLabel.ForeColorSelectColor(originalColor)titleLabel.ForeColor = ColorDialog1.Color

End Sub

Sub Procedure

CallingProcedure

Page 15: 1 R. Ching, Ph.D. MIS Dept. California State University, Sacramento Week 15 May 10 Review

15

R. Ching, Ph.D. • MIS Dept. • California State University, Sacramento

Writing Function ProceduresWriting Function Procedures

• In the Editor window enclose the linesIn the Editor window enclose the linesof code with Private Function( ) and End Function of code with Private Function( ) and End Function statementsstatements

• To use the Function, Call it by using it in an expressionTo use the Function, Call it by using it in an expression

• Pass arguments ByVal or ByRefPass arguments ByVal or ByRef

Private Function FunctionName( ) As Datatype' Statements to execute.

End Function

Page 16: 1 R. Ching, Ph.D. MIS Dept. California State University, Sacramento Week 15 May 10 Review

16

R. Ching, Ph.D. • MIS Dept. • California State University, Sacramento

Returning the Result of a FunctionReturning the Result of a Function

• To return a value to the calling procedure set up a return To return a value to the calling procedure set up a return valuevalue

• The return value will be placed by VB in a variable with The return value will be placed by VB in a variable with the SAME name as the Function's namethe SAME name as the Function's name

OROR

• Use the Return statement to return the valueUse the Return statement to return the value

Page 17: 1 R. Ching, Ph.D. MIS Dept. California State University, Sacramento Week 15 May 10 Review

17

R. Ching, Ph.D. • MIS Dept. • California State University, Sacramento

Function ExampleFunction Example

Private Sub calculateButton_Click( )Dim salesDecimal As Decimal

salesDecimal = Decimal.Parse(salesTextBox.Text)

commissionLabel.Text = Commission(salesDecimal.ToString("C"))End Sub

CallingProcedure

Private Function Commission(ByVal salesAmountDecimal As Decimal) _ As Decimal

If salesAmountDecimal < 100D ThenCommission = 0D

ElseCommission = 0.15 * salesAmountDecimal

End IfEnd Function

Function

Page 18: 1 R. Ching, Ph.D. MIS Dept. California State University, Sacramento Week 15 May 10 Review

18

R. Ching, Ph.D. • MIS Dept. • California State University, Sacramento

Functions with Multiple ArgumentsFunctions with Multiple Arguments

• Functions can receive one or more arguments (values)Functions can receive one or more arguments (values)

• Sequence and data type of arguments in Call must exactly Sequence and data type of arguments in Call must exactly match arguments in function headermatch arguments in function header

Private Function Payment(ByVal rateDecimal As Decimal, _ ByVal timeDecimal As Decimal, ByVal amountDecimal _ As Decimal) As Decimal

paymentLabel.Text = Payment(Decimal.Parse(rateTextBox.Text), _ Decimal.Parse(yearsTextBox.Text), _ Decimal.Parse(principalTextBox.Text)).ToString( )End Function

Page 19: 1 R. Ching, Ph.D. MIS Dept. California State University, Sacramento Week 15 May 10 Review

19

R. Ching, Ph.D. • MIS Dept. • California State University, Sacramento

Object-Oriented (OO) ProgramObject-Oriented (OO) Program

• ObjectsObjects

– Consist of oneConsist of oneor more dataor more datavalues whichvalues whichdefine the statedefine the stateor propertiesor propertiesof the objectof the object

– Encapsulated byEncapsulated bya set of functions (methods) that can be applied to that a set of functions (methods) that can be applied to that objectobject

DataDataDataData

MethodMethod

MethodMethod Method

Method

MethodMethod

MessageMessage

ClassClass

Page 20: 1 R. Ching, Ph.D. MIS Dept. California State University, Sacramento Week 15 May 10 Review

20

R. Ching, Ph.D. • MIS Dept. • California State University, Sacramento

Object-Oriented (OO) ProgramObject-Oriented (OO) Program

• ClassClass

– Defines:Defines:

• Characteristics of the data contained by objects of Characteristics of the data contained by objects of the classthe class

• Functions that can be applied to the objects of the Functions that can be applied to the objects of the classclass

DataDataDataData

MethodMethod

MethodMethod Method

Method

MethodMethod

DataDataDataData

MethodMethod

MethodMethod Method

Method

MethodMethod

DataDataDataData

MethodMethod

MethodMethod Method

Method

MethodMethod

ClassClass

Page 21: 1 R. Ching, Ph.D. MIS Dept. California State University, Sacramento Week 15 May 10 Review

21

R. Ching, Ph.D. • MIS Dept. • California State University, Sacramento

In VB.netIn VB.net

• Create a classCreate a class

• Define the properties of the class (Define the properties of the class (datadata))

• Build the accessor methodsBuild the accessor methods

• Build the constructorsBuild the constructorsEncapsulate the data Encapsulate the data

with methodswith methods

Page 22: 1 R. Ching, Ph.D. MIS Dept. California State University, Sacramento Week 15 May 10 Review

22

R. Ching, Ph.D. • MIS Dept. • California State University, Sacramento

Object-Oriented Terminology Object-Oriented Terminology

• Encapsulation Encapsulation

• InheritanceInheritance

• PolymorphismPolymorphism

• Reusable ClassesReusable Classes

• Multitier ApplicationsMultitier Applications

Page 23: 1 R. Ching, Ph.D. MIS Dept. California State University, Sacramento Week 15 May 10 Review

23

R. Ching, Ph.D. • MIS Dept. • California State University, Sacramento

EncapsulationEncapsulation

• Combination of characteristics of an object along with its Combination of characteristics of an object along with its behavior in "one package"behavior in "one package"

• Cannot make object do anything it does not already Cannot make object do anything it does not already "know" how to do"know" how to do

• Cannot make up new properties, methods, or eventsCannot make up new properties, methods, or events

• Sometimes referred to as data hiding; an object can expose Sometimes referred to as data hiding; an object can expose only those data elements and procedures that it wishesonly those data elements and procedures that it wishes

Page 24: 1 R. Ching, Ph.D. MIS Dept. California State University, Sacramento Week 15 May 10 Review

24

R. Ching, Ph.D. • MIS Dept. • California State University, Sacramento

EncapsulationEncapsulation

DataDataDataData

MethodMethod

MethodMethod Method

Method

MethodMethod

MessageMessage

ClassClass

Page 25: 1 R. Ching, Ph.D. MIS Dept. California State University, Sacramento Week 15 May 10 Review

25

R. Ching, Ph.D. • MIS Dept. • California State University, Sacramento

InheritanceInheritance

• Ability to create a new class from an existing classAbility to create a new class from an existing class

– Original class is called Base Class, Superclass, or Original class is called Base Class, Superclass, or Parent ClassParent Class

– Inherited class is called Subclass, Derived Class, or Inherited class is called Subclass, Derived Class, or Child ClassChild Class

• For example, each form created is inherited from the For example, each form created is inherited from the existing Form classexisting Form class

• Purpose of inheritance is reusabilityPurpose of inheritance is reusability

Page 26: 1 R. Ching, Ph.D. MIS Dept. California State University, Sacramento Week 15 May 10 Review

26

R. Ching, Ph.D. • MIS Dept. • California State University, Sacramento

Inheritance (continued)Inheritance (continued)

• Examine first line of code for a form in the EditorExamine first line of code for a form in the Editor

Public Class Form1Inherits System.Windows.Forms.Form

Inherited Class: Subclass, Derived Class, Child Class

Original Class: Base Class, Superclass, Parent Class

Page 27: 1 R. Ching, Ph.D. MIS Dept. California State University, Sacramento Week 15 May 10 Review

27

R. Ching, Ph.D. • MIS Dept. • California State University, Sacramento

Inheritance ExampleInheritance Example

• Base ClassBase Class

– PersonPerson

• SubclassesSubclasses

– EmployeeEmployee

– CustomerCustomer

– StudentStudent

Person-Name-Address-Phone

Employee StudentCustomer

PropertiesProperties

SubclassSubclass

Page 28: 1 R. Ching, Ph.D. MIS Dept. California State University, Sacramento Week 15 May 10 Review

28

R. Ching, Ph.D. • MIS Dept. • California State University, Sacramento

PolymorphismPolymorphism

• Methods having identical names but different Methods having identical names but different implementationsimplementations

• OverloadingOverloading

– Several argument lists for calling the methodSeveral argument lists for calling the method

– ExampleExample: MessageBox.Show method: MessageBox.Show method

• OverridingOverriding

– Refers to a class that has the same method name as its Refers to a class that has the same method name as its base classbase class

– Method in subclass takes precedenceMethod in subclass takes precedence

Page 29: 1 R. Ching, Ph.D. MIS Dept. California State University, Sacramento Week 15 May 10 Review

29

R. Ching, Ph.D. • MIS Dept. • California State University, Sacramento

ReusabilityReusability

• Big advantage of OOP over traditional programmingBig advantage of OOP over traditional programming

• New classes created can be used in multiple projectsNew classes created can be used in multiple projects

• Each object created from the class can have its own Each object created from the class can have its own propertiesproperties

Page 30: 1 R. Ching, Ph.D. MIS Dept. California State University, Sacramento Week 15 May 10 Review

30

R. Ching, Ph.D. • MIS Dept. • California State University, Sacramento

Decision: If StatementsDecision: If Statements

• Used to make decisionsUsed to make decisions• If true, only the Then clause is executed, if false, only Else If true, only the Then clause is executed, if false, only Else

clause, if present, is executedclause, if present, is executed• Block If…Then…Else must always conclude with End IfBlock If…Then…Else must always conclude with End If• Then must be on same line as If or ElseIfThen must be on same line as If or ElseIf• End If and Else must appear alone on a lineEnd If and Else must appear alone on a line• Note: ElseIf is 1 word, End If is 2 wordsNote: ElseIf is 1 word, End If is 2 words

Page 31: 1 R. Ching, Ph.D. MIS Dept. California State University, Sacramento Week 15 May 10 Review

31

R. Ching, Ph.D. • MIS Dept. • California State University, Sacramento

Decision: If…Then…Else – General FormDecision: If…Then…Else – General Form

If (condition) Thenstatement(s)

[ElseIf (condition) Thenstatement(s)]

[Elsestatement(s)]

End If

ConditionCondition TrueTrue

FalseFalse

StatementStatement StatementStatement

Page 32: 1 R. Ching, Ph.D. MIS Dept. California State University, Sacramento Week 15 May 10 Review

32

R. Ching, Ph.D. • MIS Dept. • California State University, Sacramento

Decision: If…Then…Else - ExampleDecision: If…Then…Else - Example

unitsDecimal = Decimal.Parse(unitsTextBox.Text)unitsDecimal = Decimal.Parse(unitsTextBox.Text)If unitsDecimal < 32D ThenIf unitsDecimal < 32D Then

freshmanRadioButton.Checked = TruefreshmanRadioButton.Checked = TrueElseElse

freshmanRadioButton.Checked = FalsefreshmanRadioButton.Checked = FalseEnd IfEnd If

Page 33: 1 R. Ching, Ph.D. MIS Dept. California State University, Sacramento Week 15 May 10 Review

33

R. Ching, Ph.D. • MIS Dept. • California State University, Sacramento

Decision: ConditionsDecision: Conditions

• Test in an If statement is based on a conditionTest in an If statement is based on a condition• Six relational operators are used for comparisonSix relational operators are used for comparison• Negative numbers are less than positive numbersNegative numbers are less than positive numbers• An equal sign is used to test for equalityAn equal sign is used to test for equality• Strings can be compared, enclose strings in quotes (see Strings can be compared, enclose strings in quotes (see

Page 142 for ANSI Chart, case matters)Page 142 for ANSI Chart, case matters)– JOAN is less than JOHNJOAN is less than JOHN– HOPE is less than HOPELESSHOPE is less than HOPELESS

• Numbers are always less than lettersNumbers are always less than letters– 300ZX is less than Porsche300ZX is less than Porsche

Page 34: 1 R. Ching, Ph.D. MIS Dept. California State University, Sacramento Week 15 May 10 Review

34

R. Ching, Ph.D. • MIS Dept. • California State University, Sacramento

Decision: The Six Relational Operators Decision: The Six Relational Operators

• Greater ThanGreater Than >>

• Less ThanLess Than <<

• Equal ToEqual To ==

• Not Equal ToNot Equal To <><>

• Greater Than or Equal ToGreater Than or Equal To >=>=

• Less Than or Equal toLess Than or Equal to <=<=

Page 35: 1 R. Ching, Ph.D. MIS Dept. California State University, Sacramento Week 15 May 10 Review

35

R. Ching, Ph.D. • MIS Dept. • California State University, Sacramento

Decision: Compound ConditionsDecision: Compound Conditions

• Join conditions using logical operatorsJoin conditions using logical operators

– OrOr If one or both conditions True, If one or both conditions True, entire condition is Trueentire condition is True

– AndAnd Both conditions must be True Both conditions must be True for entire condition to be Truefor entire condition to be True

– NotNot Reverses the condition, a Reverses the condition, a True condition will evaluate False True condition will evaluate False

and vice versaand vice versa

OR T F

T

F

T T

T F

Condition 1

Con

diti

on 2

AND T F

T

F

T F

F F

Condition 1

Con

diti

on 2

Page 36: 1 R. Ching, Ph.D. MIS Dept. California State University, Sacramento Week 15 May 10 Review

36

R. Ching, Ph.D. • MIS Dept. • California State University, Sacramento

Decision: Compound Condition ExamplesDecision: Compound Condition Examples

If maleRadioButton.Checked And _ Integer.Parse(ageTextBox.Text) < 21 Then

minorMaleCountInteger += 1End If

If juniorRadioButton.Checked Or seniorRadioButton.Checked ThenupperClassmanInteger += 1

End If

Page 37: 1 R. Ching, Ph.D. MIS Dept. California State University, Sacramento Week 15 May 10 Review

37

R. Ching, Ph.D. • MIS Dept. • California State University, Sacramento

Decision: Combining And and Or ExampleDecision: Combining And and Or Example

If saleDecimal > 1000.0 Or discountRadioButton.Checked _ And stateTextBox.Text.ToUpper( ) <> "CA" Then

' Code here to calculate the discount.End If

Page 38: 1 R. Ching, Ph.D. MIS Dept. California State University, Sacramento Week 15 May 10 Review

38

R. Ching, Ph.D. • MIS Dept. • California State University, Sacramento

If tempInteger > 32 ThenIf tempInteger > 80 Then

commentLabel.Text = "Hot"Else

commentLabel.Text = "Moderate"End If

ElsecommentLabel.Text = "Freezing"

End If

Decision: Nested If StatementsDecision: Nested If Statements

Page 39: 1 R. Ching, Ph.D. MIS Dept. California State University, Sacramento Week 15 May 10 Review

39

R. Ching, Ph.D. • MIS Dept. • California State University, Sacramento

Iteration: Do/LoopsIteration: Do/Loops

• Repeating a series of instructionsRepeating a series of instructions

• An iteration is a single execution of the statement(s) in the An iteration is a single execution of the statement(s) in the looploop

• Used when the exact number of iterations is unknownUsed when the exact number of iterations is unknown

Page 40: 1 R. Ching, Ph.D. MIS Dept. California State University, Sacramento Week 15 May 10 Review

40

R. Ching, Ph.D. • MIS Dept. • California State University, Sacramento

Iteration: Do/Loops (continued)Iteration: Do/Loops (continued)

• Terminates based on a specified conditionTerminates based on a specified condition

– Loop While a condition is TrueLoop While a condition is True

– Loop Until a condition becomes TrueLoop Until a condition becomes True

• Condition can be placed atCondition can be placed at

– Top of loop - PretestTop of loop - Pretest

– Bottom of loop - PosttestBottom of loop - Posttest

Page 41: 1 R. Ching, Ph.D. MIS Dept. California State University, Sacramento Week 15 May 10 Review

41

R. Ching, Ph.D. • MIS Dept. • California State University, Sacramento

Iteration: The Do and Loop Statements -Iteration: The Do and Loop Statements -General FormGeneral Form

Do {While |Until} Do {While |Until} conditioncondition

' ' Statements in loop.Statements in loop.

LoopLoop

OROR

DoDo

' ' Statements in loop.Statements in loop.

Loop {While | Until} Loop {While | Until} conditioncondition

Top of Loop Top of Loop Condition,Condition,

Pretest Pretest (condition (condition checked checked

beforebefore the the loop loop

execturesexecturesBottom of Bottom of

Loop Loop Condition,Condition,Posttest Posttest

(condition (condition checked after checked after

the loop the loop executes)executes)

Page 42: 1 R. Ching, Ph.D. MIS Dept. California State University, Sacramento Week 15 May 10 Review

42

R. Ching, Ph.D. • MIS Dept. • California State University, Sacramento

Iteration: Pretest vs. PosttestIteration: Pretest vs. Posttest

• Pretest, loop may never be executed since tested BEFORE Pretest, loop may never be executed since tested BEFORE runningrunning

• Do While … LoopDo While … Loop

• Do Until … LoopDo Until … Loop

• Posttest, loop will always be executed at least oncePosttest, loop will always be executed at least once

• Do … Loop WhileDo … Loop While

• Do … Loop UntilDo … Loop Until

Page 43: 1 R. Ching, Ph.D. MIS Dept. California State University, Sacramento Week 15 May 10 Review

43

R. Ching, Ph.D. • MIS Dept. • California State University, Sacramento

Iteration: Do While vs. Do UntilIteration: Do While vs. Do Until

• Do While a condition is true or falseDo While a condition is true or falseuserEntry = FalseuserEntry = FalseDo while errorFlag = FalseDo while errorFlag = False

……If len(customerName.textbox) > 0 ThenIf len(customerName.textbox) > 0 Then

……userEntry = TrueuserEntry = True

ElseElse……

End IfEnd IfLoopLoop

Condition

Condition

True

False

True

False

Loo

p

Page 44: 1 R. Ching, Ph.D. MIS Dept. California State University, Sacramento Week 15 May 10 Review

44

R. Ching, Ph.D. • MIS Dept. • California State University, Sacramento

Iteration: Do While vs. Do Until: PretestIteration: Do While vs. Do Until: Pretest

• Do While a condition is true or falseDo While a condition is true or falseuserEntry = FalseuserEntry = FalseDo until errorFlag = TrueDo until errorFlag = True

……If len(customerName.textbox) > 0 ThenIf len(customerName.textbox) > 0 Then

……userEntry = TrueuserEntry = True

ElseElse……

End IfEnd IfLoopLoop

Condition

Condition

False

True

True

False

Loo

p

Page 45: 1 R. Ching, Ph.D. MIS Dept. California State University, Sacramento Week 15 May 10 Review

45

R. Ching, Ph.D. • MIS Dept. • California State University, Sacramento

Iteration: Do While vs. Do Until: PosttestIteration: Do While vs. Do Until: Posttest

• Do While a condition is true or falseDo While a condition is true or falseuserEntry = TrueuserEntry = TrueDoDo

……If len(customerName.textbox) > 0 ThenIf len(customerName.textbox) > 0 Then

……userEntry = TrueuserEntry = True

ElseElse……

End IfEnd IfLoop Until userEntry = TrueLoop Until userEntry = True

(or Loop While userEntry = False)(or Loop While userEntry = False) Condition

True

False

True

False

Loo

p

userEntry = True

Condition

Page 46: 1 R. Ching, Ph.D. MIS Dept. California State University, Sacramento Week 15 May 10 Review

46

R. Ching, Ph.D. • MIS Dept. • California State University, Sacramento

Iteration: For/Next LoopsIteration: For/Next Loops

• Use when you know the number of iterationsUse when you know the number of iterations

• Uses a numeric counter variable, called Loop Index, to Uses a numeric counter variable, called Loop Index, to control number of iterationscontrol number of iterations

• Loop Index is incremented at the bottom of the loop on Loop Index is incremented at the bottom of the loop on each iteration each iteration

• Step value can be included to specify the incrementing Step value can be included to specify the incrementing amount to increment Loop Index, step can be a negative amount to increment Loop Index, step can be a negative numbernumber

Page 47: 1 R. Ching, Ph.D. MIS Dept. California State University, Sacramento Week 15 May 10 Review

47

R. Ching, Ph.D. • MIS Dept. • California State University, Sacramento

Iteration: The For and Next Statements - Iteration: The For and Next Statements - General FormGeneral Form

For For LoopIndexLoopIndex = = InitialValue InitialValue ToTo TestValue TestValue [Step [Step IncrementIncrement]] ' ' Statements in loop.Statements in loop.

Next [LoopIndex]Next [LoopIndex]

Page 48: 1 R. Ching, Ph.D. MIS Dept. California State University, Sacramento Week 15 May 10 Review

48

R. Ching, Ph.D. • MIS Dept. • California State University, Sacramento

Iteration: For/Next LoopIteration: For/Next Loop

• For example:For example:

Dim customerCount as IntegerDim customerCount as Integer

For customerCount = 1 to 10For customerCount = 1 to 10......If customerType = “Regular” ThenIf customerType = “Regular” Then

……ElseElse

End IfEnd IfNextNext

Page 49: 1 R. Ching, Ph.D. MIS Dept. California State University, Sacramento Week 15 May 10 Review

49

R. Ching, Ph.D. • MIS Dept. • California State University, Sacramento

Iteration: Exiting For/Next LoopsIteration: Exiting For/Next Loops

• In some situations you may need to exit the loop In some situations you may need to exit the loop prematurelyprematurely

• Use the Use the Exit ForExit For statement inside the loop structure statement inside the loop structure

• Generally the Exit For statement is part of an If statementGenerally the Exit For statement is part of an If statement