CIS 115 Lecture 8 Repetition Looping Control Structures

















![For Next Statement Syntax (counted) For Counter = Start. Value To End. Value[Step Value] For Next Statement Syntax (counted) For Counter = Start. Value To End. Value[Step Value]](https://slidetodoc.com/presentation_image_h/79e79e816ff668041e72bb44eac1016b/image-18.jpg)








- Slides: 26

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

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 True expression False statement(s)

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 int. Count = 1 Do While (int. Count <= 10) Msg. Box (“The current number is: “ & int. Count) int. Count = int. Count + 1 Loop ----------------------------int. Num. Grades = 0, int. Sum. Grades = 0 str. Input = Input. Box(“Enter a grade(or -1 to stop)”) Do While (str. Input <> “-1”) int. Sum. Grades = int. Sum. Grades + Val(str. Input) int. Num. Grades = int. Num. Grades + 1 str. Input = Input. Box(“Enter a grade(or -1 to stop)”) Loop dec. Average = int. Sum. Grades / int. Num. Grades Msg. Box(“Your average is: “ & dec. Average)

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 int. Count increases by one for each repetition Finally (int. Count <= 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 int. Count from the previous example Counters are typically initialized before the loop begins int. Count = 1 The counter is then modified in the body of the loop int. Count = int. Count + 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 int. Num. Grades 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 int. Sum. Grades 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) False expression 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 int. Count = 1 Do Msg. Box (“The current number is: “ & int. Count) int. Count = int. Count + 1 Loop Until (int. Count > 10) ----------------------------int. Num. Grades = 0, int. Sum. Grades = 0 Do str. Input = Input. Box(“Enter a grade(or -1 to stop)”) If (str. Input <> “-1”) Then int. Sum. Grades = int. Sum. Grades + Val(str. Input) int. Num. Grades = int. Num. Grades + 1 End If Loop Until (str. Input = “-1”) dec. Average = int. Sum. Grades / int. Num. Grades Msg. Box(“Your average is: “ & dec. Average)

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, Do but also has a postest form: statement(s) Loop While expression A Do Until loop Repeats as long as its test expression is false Ends when its test expression becomes true Usually a posttest loop, Do Until expression but also has a pretest form: statement(s) Loop

More Do While and Do Until Examples Do str. Input. PW = Input. Box(“Enter Password”) Loop Until (str. Input. PW = str. Saved. PW) str. Input. PW = Input. Box(“Enter Password”) Do While (str. Input. PW <> str. Saved. PW) str. Input. PW = Input. Box(“Enter Password”) Loop ----------------------------Do While (dec. Balance < 0) int. Dep = Input. Box(“Negative balance, enter amount to deposit”) dec. Balance += dec. Dep Loop

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 Start. Value 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 End. Value is exceeded Set Counter to Start. Value Increment Counter > End. Value? True False statement(s)
![For Next Statement Syntax counted For Counter Start Value To End ValueStep Value For Next Statement Syntax (counted) For Counter = Start. Value To End. Value[Step Value]](https://slidetodoc.com/presentation_image_h/79e79e816ff668041e72bb44eac1016b/image-18.jpg)
For Next Statement Syntax (counted) For Counter = Start. Value To End. Value[Step Value] statement[s] Next [Counter] Syntax explanation: For, To, and Next are keywords Counter – Variable to track/control number of iterations Start. Value is initial value of counter End. Value 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 int. Count = 1 to 10 Step 1 msg. Box (“The current number is: “ & int. Count) Next -----------------------------For int. Count = 100 to 0 Step -5 msg. Box (“The current number is: “ & int. Count) Next -----------------------------int. Sum = 0 int. Num = Val(Input. Box(“Enter number of grades to avg”)) For int. Count = 1 to int. Num Step 1 str. Input = Input. Box(“Enter a grade”) int. Sum = int. Sum + Val(str. Input) Next dec. Average = int. Sum / int. Num Msg. Box(“Your average is: “ & dec. Average)

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) str. Input = Input. Box(“Enter a grade(or -1 to stop)”) If (str. Input = “-1”) Then Exit Do End If int. Sum. Grades = int. Sum. Grades + Val(str. Input) int. Num. Grades = int. Num. Grades + 1 Loop dec. Average = int. Sum. Grades / int. Num. Grades Msg. Box(“Your average is: “ & dec. Av

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 str. Output = “” For int. Tens. Place = 0 to 4 Step 1 For int. Ones. Place = 0 to 9 Step 1 str. Output &= (int. Tens. Place & int. Ones. Place & “ “) Next Msg. Box(“I can count from 0 to 49: ” & str. Output) -----------------------------For hours = 0 To 24 lbl. Hours. Text = hours For minutes = 0 To 59 lbl. Minutes. Text = minutes For seconds = 0 To 59 lbl. Seconds. Text = 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 t 0 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?