# Unit V (Repetition)

## Day 15 — Unit V Introduction

• Roll

### Review Unit IV Competency Demo

• Review each item
• Respond to questions

### Repetition Concepts

We are getting close to the end of the "basics of computing"—actions & data, sequence, selection, iteration, and modularization. We keep finding out about more things we can use in the actions (controls and properties) and seeing ways to organize the actions. Again, the basics are data & actions and organizing the actions (on data). Remember, the hardest part of programming is determining precisely what we want to accomplish.

Repetition is merely doing some task over and over again. For example:

• flip a coin 10 times
• process individual characters in a piece of text
• search items in a listbox (to find a particular value)
• process all the lines in a file
• repeatedly present arithmetic practice problems

There are many different versions of loops. For us, it seems reasonable to concentrate on three of them. The `For ... Next` loop, the `Do While...` loop, and the `Do Until ...` loop.

Show equivalent examples that count to 10.

• For loop
```    Dim i As Integer
For i = 1 to 10
MessageBox.Show(i)
Next i           ' you may omit the "i" here if you wish
```
• Do While loop
```    Dim i as Integer
i = 1
Do While i <= 10
MessageBox.Show(i)
i = i + 1
Loop
```
• Do Until loop
```    Dim i as Integer
i = 1
Do Until i > 10
MessageBox.Show(i)
i = i + 1
Loop
```

The for loop will initialize and increment the counter variable. You must do those yourself if you choose to use the do while or do until loop.

### Roles of Variables

Our programs are now getting more complex. Before we address additional repetition examples I want to briefly describe the roles for which we most often use variables. The hope is that by mentioning these roles to you, the algorithms and programs that use them will make a bit more sense to you. The primary roles for variables are: (see The Roles of Variables Home Page for further info.)

• fixed value

a variable that gets a value and does not change thereafter;  e.g., `salesTaxRate`, ...

• stepper

a variable used to systematically access each of a succession of values ;  e.g., `count`, `timer`, ...

• gatherer

a variable that accumulates a value while processing a success of values;  e.g., `sum`, ...

• temporary

a variable used as a value holder for a very short time (often used to swap one value with another);  e.g., `temp`, ...

• one-way flag

a variable indicating success or failure—starts as true or false and only changes to the other value (does not go back to the original value;  e.g., `orderOkay`, `errorFound`, ...

• most-recent holder

a variable that contains/records/holds the latest value to be examined or entered;  e.g., `userInput`, `current`, ...

• most-wanted holder

a variable containing the current value of the "best" value sought;  e.g., `best`, `least`, ...

• follower

a variable container the value prior to the "current" value (will usually get set to the current value)—it is used to remember what happened in the previous program state or iteration;  e.g., `lastFlip`, `previous`, ...

### Planning and Implementing repetition

We must remember that the programming fundamental of sequence, must be considered for iteration to work correctly, you must carefully determine and place the actions necessary to accomplish your task. Some actions will need to be done before the repetition, some during the repetition, and some after the repetition. If you do not put all the actions in the right place, the overall result will not be correct.

#### Key idea # 1 in repetition—know precisely what you want to repeat

Clearly you have to tell the computer what you want it to repeat, DUH! Remember, the computer does what it is told to do—exactly what it is told and only what it is told. Be careful that you put only the actions you want repeated inside the loop. Some things should go before or after the loop.

Also, if something has to be done to be ready for the next repetition your code must include that. So think carefully about whether something needs to occur to be ready for the next iteration of the loop code. If there some such code, it should most likely be placed just before the end of the loop.

#### Key idea # 2 in repetition—determine when to stop repeating

Another critical consideration in iteration is determining when to stop or how many times to repeat something. If you want to process the items in a collection or lines in a file, you just keep processing until you've processed them all. Sometimes you can do that by using a counting loop and sometimes you don't know or cannot tell how many items there are and so must devise some sort of conditional expression to tell you when you are done. That leads to our next key idea. You may keep repeating until the user enters a particular value or until a particular value is found or ... Just be sure to pay attention to the condition for stopping the loop.

#### Key idea # 3 in repetition—initialize

Your code has to include any and all the actions that need to come before the loop (ofter referred to as initialization). If you are counting things, the counter needs to be set to 0. If you are searching for a value, you have to get the value to be searched for. If you are checking for errors you will need to set an error flag to `True` or `False` before you start.

#### Key idea # 4 in repetition—after the loop

Finally, there is almost always some action that needs to be done after the loop. Reporting the result from the repetition is usually called for. Sometimes repetition had two tests for determining when to stop, e.g., look at the items to see if a particular value is included. In this case we would want to stop when we found it or when we had looked at all the values. After the loop, we know we stopped but we don't know why we stopped. We will need to test (using an `If`) to see why we stopped and take the appropriate action.

### Examples

We are going to show some examples that illustrate the key ideas and the Visual Basic code for iteration. We will use the idea of coin flipping simulations in all of them. The plan for each is to:

• analyze the problem, making sure we understand it
• determine the actions that need to be repeated
• decide how we will to control the repetition
• determine the actions needed before the loop
• determine the actions needed after the loop
• code the solution
• test and debug the solution, making sure it seems/is correct

The examples are:

o
• flip a coin 1,000 times counting the numbers of heads and tails

We will need counts for heads and tails and a mechanism for deciding heads or tails. (I will just check the value produced by `Rnd()`.) We also need to remember to `Randomize`. An algorithm using a counting loop is:

```                    ' happens BEFORE the loop
tailCount ← 0     '..... gatherer
for  count ← 1 to 1000     '..... count is a stepper
' happens INSIDE the loop
if Rnd() < 0.5
else
tailCount ← tailCount + 1
' happens AFTER the loop
```

Code & test the algorithm.   Comments/Questions/Wonderings?

• flip a coin the number of times desired by the user, counting the numbers of heads and tails

This is almost identical to the above problem. We have to get a number-of-repetitions value from the user (input box?) and and change loop parameters to one with a variable. An algorithm is:

```                    ' happens BEFORE the loop
tailCount ← 0
repsLimit ← userInput     '..... fixed value

for  count ← 1 to repsLimit
' happens INSIDE the loop
if Rnd() < 0.5
else
tailCount ← tailCount + 1

' happens AFTER the loop
```

Remember that Unit V is about repetition, but, the repetition itself is relatively easy (in this case), it is the stuff before, during, and after the repetition that causes any difficulty. Any questions or wonderings?

Code & test the algorithm.   Comments/Questions/Wonderings?

• flip a coin 1,000 times, counting the numbers of heads and tails and record the longest sequence of heads in a row and the longest sequence of tails in a row

This introduces two new things that have nothing to do with the repetition—keeping track of the flips in a row and determining the longest such sequence.

Develop the algorithm on the board to show the thinking and development process. Hopefully, it looks something like the following when done.

```                    ' happens BEFORE the loop
tailCount ← 0
consecHeads ← 0   '..... a gatherer
consecTails ← 0   '..... a gatherer
mostHeads ← 0     '..... a most-wanted holder
mostTails ← 0     '..... a most-wanted holder
currFlip ← ""     '..... a most-recent holder
lastFlip ← ""     '..... a follower

for  count ← 1 to 1000
' happens INSIDE the loop
if  Rnd() < 0.5
consecTails ← 0
else
else
tailCount ← tailCount + 1
currFlip ← tails
if lastFlip = tails
consecTails ← consecTails + 1
if consecTails > mostTails
mostTails ← consecTails
else
consecTails ← 1
lastFlip ← tails

' happens AFTER the loop
```

Now all we have to do it put it all together! Code & test the algorithm Comments/Questions/Wonderings?

• flip a coin until you get `n` in a row (get the value of `n` from the user)

Now that we know how to keep track of runs we can try an indefinite loop. We keep repeating until an end condition is met or as long as a continue condition is true. An algorithm is:

```                    ' happens BEFORE the loop
tailCount ← 0
consecTails ← 0
currFlip ← ""
lastFlip ← ""
consecGoal ← userInput     '..... fixed value

repeat until  consecHeads >= consecGoal or consecTails >= consecGoal
' happens INSIDE the loop
if  Rnd() < 0.5
consecTails ← 0
else
else
tailCount ← tailCount + 1
currFlip ← tails
if lastFlip = tails
consecTails ← consecTails + 1
else
consecTails ← 1
lastFlip ← tails

' happens AFTER the loop
```

Now all we have to do it put it all together! Be careful not to ask for many in a row, maybe only 10 or 12. Code & test the algorithm Comments/Questions/Wonderings?

### Next Time

• Questions & work on Unit V learning activity

## Day 16 — Unit V Work

• Roll

### Plans for Unit V

Now that we've had an introduction, I want to do a couple examples that involve processing things, i.e., the items in a list box the characters in a string. After that, you will have the rest of the period for working on your practice activity. Code for the examples done is included below.

• process items in a list
```    Dim report As String = ""
Dim count As Integer = 0
For i As Integer = 0 To lstOrder.Items.Count - 1
If Val(lstOrder.Items(i)) Mod 2 <> 0 Then
report = report & lstOrder.Items.Item(i) & vbNewLine
count += 1
End If
Next
MessageBox.Show("there were " & count.ToString _
& " odd numbers in the list, i.e., " & vbNewLine _ & report)
```
• count vowels in a string
```    Dim mystr As String = txtStrInput.Text.ToLower
Dim vowels As Integer = 0
Dim vowelValues As String = "aeiouy"
For i As Integer = 0 To mystr.Length - 1
For j As Integer = 0 To vowelValues.Length - 1
If (mystr.Chars(i)) = vowelValues.Chars(j) Then
vowels += 1
End If
Next
Next
MessageBox.Show(vowels.ToString)
```

The plan is that you will have tried to do all the practice activity before next class class period and bring any questions you have to class.

### Next Time

• Address questions & work on Unit V learning activity

## Day 17 — Unit V Work

• Roll

### Today's Activities

The plan for today is to:  1) respond to any questions you have on the Unit V practice activity;  2) discuss a sample Unit V competency demo;  allow time to work on the practice activity

• Any questions on or issues with any of the practice activity items?
• Display sample competency demo and address any questions.
• Students work on the practice activity.

### Next Time

• Unit V competency demo I.a
• Formally introduce files and arrays

• Roll