Date post: | 12-Jan-2016 |
Category: |
Documents |
Upload: | grant-patrick |
View: | 225 times |
Download: | 0 times |
CIS 115 Lecture 8
There are 3 control structures common to most computer languages that determine the flow, or path of execution, of the code:
Sequential
Selection / Decisions
Repetition / Looping
Visual Basic repetition or looping statements Do While
▪ Repeat/Loop while true▪ Often called pretest loop (also has posttest
form) Do Until
▪ Repeat/Loop until true▪ Often called posttest loop (also has pretest
form) For...Next
▪ Repeat/Loop a specified number of times
Do While loop: repeat while test expression is true
The test expression is evaluated (pretest) When true, the statement(s)are executed The previous 2 steps are repeated as long
as the expression evaluates to true
When false, theloop ends andthe statement(s)are not executed
expression statement(s)
False
True
Do While expressionstatement(s)
Loop Syntax explanation:
Do, While, and Loop are keywords Do While statement marks the beginning of the
loop and the Loop statement marks the end The statement(s) to repeat are found between
these and called the body of the loop Expression – True/False value, variable,
function call or expression that serves as test for repetition
intCount = 1Do While (intCount <= 10) MsgBox (“The current number is: “ & intCount) intCount = intCount + 1Loop---------------------------------------------------------intNumGrades = 0, intSumGrades = 0strInput = InputBox(“Enter a grade(or -1 to stop)”) Do While (strInput <> “-1”)
intSumGrades = intSumGrades + Val(strInput)intNumGrades = intNumGrades + 1
strInput = InputBox(“Enter a grade(or -1 to stop)”)LoopdecAverage = intSumGrades / intNumGradesMsgBox(“Your average is: “ & decAverage)
A loop must have some way to end itself Something within the body of the loop
must eventually force the test expression to false
In the previous example The loop continues to repeat intCount increases by one for each repetition Finally (intCount <= 10) is false and the loop
ends If the test expression can never be false,
the loop will continue to repeat forever This is called an infinite loop
Counter-controlled loops repeat a specific number of times
see intCount from the previous example Counters are typically initialized before the loop
beginsintCount = 1
The counter is then modified in the body of the loop
intCount = intCount + 1
Event-controlled loops repeat until something happens in the loop body
to change the value of loop control variable Events can be: User Input, Expression results,
Function results, etc.
Sentinel Value For either control type, the test expression
will usually determine when to end the loop by making some comparison to a Sentinel value
The sentinel value serves as the test value or comparison criteria for ending the loop▪ In counted loops this is usually the number of
times to loop▪ In event controlled loops this is the state or value
that the event variable is compared to in the test expression
Counter A numeric variable that keeps track of or
counts: number of loop repetitions, items that have been processed, or some other occurrence within a loop
see intNumGrades from the previous example
Accumulator A numeric variable that is used to hold a
sub-total that is computed during multiple passes through a loop
see intSumGrades from the previous example
Do Until loop: repeat until test expression is true
The statement(s)are executedThe test expression is
evaluated (posttest)When false, the previous 2
steps are repeated until theexpression evaluates to true
When true, the loop ends andthe statement(s) are notexecuted again
expression
statement(s)
False
True
Dostatement(s)
Loop Until expression Syntax explanation:
Do, Loop, and Until are keywords Do statement marks the beginning of the loop
and the Loop Until statement marks the end The statement(s) to be repeated are found
between these and called the body of the loop Expression – True/False value, variable,
function call or expression that serves as test for repetition
intCount = 1Do
MsgBox (“The current number is: “ & intCount) intCount = intCount + 1Loop Until (intCount > 10)---------------------------------------------------------intNumGrades = 0, intSumGrades = 0Do strInput = InputBox(“Enter a grade(or -1 to stop)”)
If (strInput <> “-1”) ThenintSumGrades = intSumGrades + Val(strInput)intNumGrades = intNumGrades + 1
End IfLoop Until (strInput = “-1”)decAverage = intSumGrades / intNumGradesMsgBox(“Your average is: “ & decAverage)
Previous Do While loops are in pretest form The expression is evaluated first Then the loop body is executed only if expression is
true The body of a pretest loop may not be
executed at all (if initial value of expression is false)
Previous Do Until loops are in posttest form The body of the loop is executed first Then the expression is evaluated The body of a posttest loop is executed at
least once (even if initial value of expression is true)
A Do While loop Repeats as long as its test expression is true Ends when its test expression becomes false Usually a pretest loop,
but also has a postest form:
A Do Until loop Repeats as long as its test expression is
false Ends when its test expression becomes true Usually a posttest loop,
but also has a pretest form:
Do Until expressionstatement(s)
Loop
Dostatement(s)
Loop While expression
Do strInputPW = InputBox(“Enter Password”)
Loop Until (strInputPW = strSavedPW)
strInputPW = InputBox(“Enter Password”)Do While (strInputPW <> strSavedPW)
strInputPW = InputBox(“Enter Password”)Loop
---------------------------------------------------------
Do While (decBalance < 0)intDep = InputBox(“Negative balance, enter amount to deposit”)decBalance += decDep
Loop
For Next loop: used for counted loops that repeat a specific number of times
The Counter variable is setinitially to the StartValue
After each loop iteration, the Step Value is added tothe value of the countervariable. (if there is no stepvalue, 1 is added)
Iteration continues until theEndValue is exceeded
Counter >EndValue?
statement(s)False
True
SetCounter
to StartValue
IncrementCounter
For Counter = StartValue To EndValue[Step Value]statement[s]
Next [Counter]
Syntax explanation: For, To, and Next are keywords Counter – Variable to track/control number of
iterations StartValue is initial value of counter EndValue is counter value at final iteration Step (optional) – determines counter increment
amount for each iteration of the loop (if not specified the default is +1; if specified can be positive – add or count up, or negative – subtract or count down
For intCount = 1 to 10 Step 1msgBox (“The current number is: “ & intCount)
Next----------------------------------------------------------For intCount = 100 to 0 Step -5msgBox (“The current number is: “ & intCount)
Next----------------------------------------------------------intSum = 0intNum = Val(InputBox(“Enter number of grades to avg”))For intCount = 1 to intNum Step 1strInput = InputBox(“Enter a grade”)intSum = intSum + Val(strInput)
NextdecAverage = intSum / intNumMsgBox(“Your average is: “ & decAverage)
In some cases it is convenient to end a loop before the test condition would end it
The following statements accomplish this Exit Do (used in Do While or Until loops) Exit For (used in For Next loops)
Use this capability with caution It bypasses normal loop termination Makes code more difficult to debug
Do While (true)strInput = InputBox(“Enter a grade(or -1 to stop)”)If (strInput = “-1”) Then
Exit DoEnd IfintSumGrades = intSumGrades + Val(strInput)intNumGrades = intNumGrades + 1
LoopdecAverage = intSumGrades / intNumGradesMsgBox(“Your average is: “ & decAv
The body of a loop can contain any type of VB statements including another loop
When a loop is found within the body of another loop, it’s called a nested loop
strOutput = “”For intTensPlace = 0 to 4 Step 1For intOnesPlace = 0 to 9 Step 1
strOutput &= (intTensPlace & intOnesPlace & “ “)Next
NextMsgBox(“I can count from 0 to 49: ” & strOutput)----------------------------------------------------------For hours = 0 To 24lblHours.Text = hoursFor minutes = 0 To 59
lblMinutes.Text = minutesFor seconds = 0 To 59
lblSeconds.Text = secondsNext seconds
Next minutesNext hours
Have the user input a positive number via input box. Use a validation loop to prompt for input until valid. Display message indicating when valid input is received.
Have the user input numbers via inputbox until the value “stop” is entered. Display the sum of all the input numbers.
Have the user input an integer. Display the sum of all the integers from 1 through the input integer.
Have the user input a yearly deposit amount and a yearly interest rate. Use a loop to determine the min number of years it will take to reach at least 1 million $ (for each year – add dep first, then compute and add int). Display the number of years and the final value. Modify to have the user also enter a number of years and display the final value after that number of years.
Write a VB application to have the user input via textbox an integer from 1 t0 10 (inclusive) to specify the height and base of a right triangle. Display the triangle in a list box using strings made up of the ‘#’ character. Create and display strings - one char at a time - using nested loops. Input:4 Output:
##########
Write a VB application to have the user input a binary number via input box. Use a validation loop ensure the input is a valid binary number. When valid, convert the number to a decimal value (use a function) and report the results via message box.
Lab 7 and Homework 7 Visual Basic – Looping See handout for details and due date Questions?