270 likes | 704 Views
CIS 115 Lecture 8. Repetition / Looping. Control Structures. 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. VB Repetition.
E N D
CIS 115 Lecture 8 Repetition / Looping
Control Structures 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
VB Repetition • 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
expression statement(s) True False Do While Looping Structure • 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, the loop ends and the statement(s) are not executed
Do While Statement Syntax (pretest) Do While expression statement(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
Do While Examples intCount = 1 Do While (intCount <= 10) MsgBox (“The current number is: “ & intCount) intCount = intCount + 1 Loop --------------------------------------------------------- intNumGrades = 0, intSumGrades = 0 strInput = 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)”) Loop decAverage = intSumGrades / intNumGrades MsgBox(“Your average is: “ & decAverage)
Infinite Loops • 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
Controlling Loops • Counter-controlled loops • repeat a specific number of times see intCount from the previous example • Counters are typically initialized before the loop begins intCount = 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.
Controlling Loops (cont.) • 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
Counters and Accumulators • 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 Looping Structure • Do Until loop: repeat until test expression is true • The statement(s)are executed • The test expression is evaluated (posttest) • When false, the previous 2 steps are repeated until the expression evaluates to true • When true, the loop ends and the statement(s) are not executed again statement(s) expression False True
Do Until Statement Syntax (posttest) Do statement(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
Do Until Examples intCount = 1 Do MsgBox (“The current number is: “ & intCount) intCount = intCount + 1 Loop Until (intCount > 10) --------------------------------------------------------- intNumGrades = 0, intSumGrades = 0 Do strInput = InputBox(“Enter a grade(or -1 to stop)”) If (strInput <> “-1”) Then intSumGrades = intSumGrades + Val(strInput) intNumGrades = intNumGrades + 1 End If Loop Until (strInput = “-1”) decAverage = intSumGrades / intNumGrades MsgBox(“Your average is: “ & decAverage)
Pretest vs. Posttest Loops • 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)
Do Until vs. Do While • 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 statement(s) Loop While expression Do Until expression statement(s) Loop
More Do While and Do Until Examples 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
Set Counter to StartValue Increment Counter Counter > EndValue? statement(s) False True For Next Looping Structure • For Next loop: used for counted loops that repeat a specific number of times • The Counter variable is set initially to the StartValue • After each loop iteration, the Step Value is added to the value of the counter variable. (if there is no step value, 1 is added) • Iteration continues until the EndValue is exceeded
For Next Statement Syntax (counted) 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 Next Examples For intCount = 1 to 10 Step 1 msgBox (“The current number is: “ & intCount) Next ---------------------------------------------------------- For intCount = 100 to 0 Step -5 msgBox (“The current number is: “ & intCount) Next ---------------------------------------------------------- intSum = 0 intNum = Val(InputBox(“Enter number of grades to avg”)) For intCount = 1 to intNum Step 1 strInput= InputBox(“Enter a grade”) intSum = intSum + Val(strInput) Next decAverage = intSum / intNum MsgBox(“Your average is: “ & decAverage)
Exiting a Loop Prematurely • 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
Exiting a Loop Examples Do While (true) strInput = InputBox(“Enter a grade(or -1 to stop)”) If (strInput = “-1”) Then Exit Do End If intSumGrades = intSumGrades + Val(strInput) intNumGrades = intNumGrades + 1 Loop decAverage = intSumGrades / intNumGrades MsgBox(“Your average is: “ & decAv
Nested Loops • 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
Nested Examples strOutput = “” For intTensPlace = 0 to 4 Step 1 For intOnesPlace = 0 to 9 Step 1 strOutput &= (intTensPlace & intOnesPlace & “ “) Next Next MsgBox(“I can count from 0 to 49: ” & strOutput) ---------------------------------------------------------- For hours = 0 To 24 lblHours.Text = hours For minutes = 0 To 59 lblMinutes.Text = minutes For seconds = 0 To 59 lblSeconds.Text = seconds Next seconds Next minutes Next hours
Example Looping Problems 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.
Example Looping Problems 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.
Homework • Lab 7 and Homework 7 • Visual Basic – Looping • See handout for details and due date • Questions?