do/loops a loop repeats a series of instructions. an iteration is a single execution of the...
Post on 19-Dec-2015
218 Views
Preview:
TRANSCRIPT
Do/Loops
• A loop repeats a series of instructions.• An iteration is a single execution of the statement(s) in the
loop.• Used when the exact number of iterations is unknown• A Do/Loop terminates based on a specified condition.
• Execution of the loop continues while a condition is True or until a condition is True.
• The condition can be placed at the top or the bottom of the loop.
The Do and Loop Statements — General Form
Do {While |Until} condition ' Statements in loop.
Loop
--OR--
Do ' Statements in loop.
Loop {While | Until} condition
Top of Loop Condition,
Pretest/Entry test
Bottom of Loop
Condition,Posttest/ Exit
Pretest vs. Posttest
• Pretest — loop may never be executed since tested BEFORE running.
Do While … LoopDo Until … Loop
• Posttest — loop will always be executed at least once.
Do … Loop WhileDo … Loop Until
Pretest vs. Posttest Diagram
The Boolean Data Type Revisited
• Can help when searching a list for a specific value• Boolean variable is always in one of two states: True or
False.• When a particular situation occurs, set Boolean variable to
True.• Use a loop to check for True
• Many programmers refer to Boolean variables as switches or flags.
• Switches have two states — on or off.• Flags are considered either up or down.
For/Next Loops
• Used to repeat statements in a loop a specific number of times
• Uses a numeric counter variable, called Loop Index, which is tested to determine the number of times the statements inside the loop will execute
• Loop Index is incremented at the bottom of the loop on each iteration.
• Step value can be included to specify the incrementing amount to increment Loop Index, step can be a negative number.
The For and Next Statements — General Form
For LoopIndex [As DataType] = InitialValue To TestValue [Step Increment]
' Statements in loop.Next [LoopIndex]
A For/Next loop can handle all three elements of a counter-controlled loop.
Initialize the counter.
Increment the counter.
Test the counter to determine when it is time to terminate the loop.
For/Next Loop Diagram
Exiting Loops
• In some situations, you may need to exit the loop prematurely.
• Click on the form’s close box or use the VB menu bar or toolbar to stop the program; or Ctrl+Break.
• Use the Exit For statement inside the loop structure.• Generally, the Exit For statement is part of an If statement.
top related