Visual Basic

Download Report

Transcript Visual Basic

Repetition Statements
 Repeating an Action
 A specified number of times
 While a Condition is True
 Until a Condition is True
3 Requirements for a Successful
Loop
 Initialize a Loop Control Variable
 Test the Loop Control Variable against an Exit
Condition
 Update the Loop Control Variable
 Must be approaching exit criteria
Counted / For Loop
 Specified Number of Times
 Syntax:
For loopVariable = start To End [Step StepValue]
Statements
Next [loopVariable]
 [ ] means optional
Example
For counter = 1 to 10 Step 1
msgBox (“The current number is: “ & counter)
Next
Try It
 Write 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 Again
 Write 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 Loops
 Continue Looping While a Condition is True
 Syntax:
Do While (condition statement)
statements
Loop
Pre-Test Loop
 In a While Loop the Loop Exit condition is tested
before the program enters the loop
 Pre-Test Loop
 If Condition is False, the Loop code may never execute
Minimum number of executions of loop is 0
Example
Do While (number <=10)
MsgBox (“The current number is: “ & number)
number = number + 1
Loop
Try It
 Write 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 Again
 Write 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 Loop
 Continues Executing Until a Condition is True
 Syntax
Do
statements
Loop Until (condition)
Post Test Loop
 In a Do..Until Loop the loop checks Exit Condition
After the Loop Executes
 Post Test Loop
 Minimum Number of Executions of Loop is 1
Example
Dim strPassword
Do
strPassword = InputBox (“Enter Password”)
Loop Until (strPassword = “Friday”)
Try It
 Note: All Loops can be written as Do While Loops
 Practice 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 Loops
 3 Requirements for Successful Loop
 Initialize a Loop Control Variable
 Test the Loop Control Variable against an Exit
Condition
 Update the Loop Control Variables
 3 Types of Loops
 Counted Loop – executes a specific number of times
 While Loop – Pre-test loop
 Do Until Loop – Post-test loop
 ALL Loops can be written as While Loops