Repetition StatementsRepeating an Action
A specified number of timesWhile a Condition is TrueUntil a Condition is True
3 Requirements for a Successful LoopInitialize a Loop Control VariableTest the Loop Control Variable against an
Exit ConditionUpdate the Loop Control Variable
Must be approaching exit criteria
Counted / For LoopSpecified Number of TimesSyntax:
For loopVariable = start To End [Step StepValue]
StatementsNext [loopVariable]
[ ] means optional
Try ItWrite a program that uses a counted/for loop
to read in a 5 numbers (using an inputBox) and display their average in a label.
Try it AgainWrite a program using a counted/for loop
that will add the numbers from 1 – 50 and display the output in a label.
Write a program using a counted/for loop that will add the odd numbers from 1 – 50 and display the output in a label.
While LoopsContinue Looping While a Condition is TrueSyntax:
Do While (condition statement)statements
Loop
Pre-Test LoopIn a While Loop the Loop Exit condition is
tested before the program enters the loopPre-Test LoopIf Condition is False, the Loop code may never
execute Minimum number of executions of loop is 0
Try ItWrite a program to require the user to enter
a correct password (“Friday”). When they enter the correct password the program will display “Have a Great Week-end”.
Try it AgainWrite a program that will calculate the
number of years it will take for a given input deposit amount to increase to a million dollars at 6% annual interest.
Test $100,000 should take 40 years
Do Until LoopContinues Executing Until a Condition is
True
Syntax
Dostatements
Loop Until (condition)
Post Test LoopIn a Do..Until Loop the loop checks Exit
Condition After the Loop ExecutesPost Test LoopMinimum Number of Executions of Loop is 1
ExampleDim strPassword
DostrPassword = InputBox (“Enter Password”)
Loop Until (strPassword = “Friday”)
Try ItNote: All Loops can be written as Do While
LoopsPractice this example using a D0 Until Loop
Write a program that reads in a list of positive integers from the user until the user enters the value of -1 (a sentinel value – exit value). At that time the program should display the largest value in the input list.
Review of Loops3 Requirements for Successful Loop
Initialize a Loop Control VariableTest the Loop Control Variable against an Exit
ConditionUpdate the Loop Control Variables
3 Types of LoopsCounted Loop – executes a specific number of
timesWhile Loop – Pre-test loopDo Until Loop – Post-test loop
ALL Loops can be written as While Loops