+ All Categories
Home > Documents > Iteration/repetition/looping Loop control variabledjmoon/vb/vb-notes/c6-iteration.pdf ·...

Iteration/repetition/looping Loop control variabledjmoon/vb/vb-notes/c6-iteration.pdf ·...

Date post: 16-Mar-2018
Category:
Upload: vanthuan
View: 229 times
Download: 1 times
Share this document with a friend
21
Iteration: Intro Iteration/repetition/looping: Executing a sequence of instructions multi- ple times Loop components: Condition: determines whether loop should continue Body: instructions being repeated Loop control variable (LCV): its value determines when loop stops Basic steps of loop control: Initialize Process Initialize LCV BEGIN LOOP Update Process Update LCV END LOOP Two types of loops: 1. Pretest Condition precedes body Iterates 0+ times This is the most general type of loop 1
Transcript

Iteration: Intro

• Iteration/repetition/looping: Executing a sequence of instructions multi-ple times

• Loop components:

– Condition: determines whether loop should continue

– Body: instructions being repeated

– Loop control variable (LCV): its value determines when loop stops

• Basic steps of loop control:

Initialize Process

Initialize LCV

BEGIN LOOP

Update Process

Update LCV

END LOOP

• Two types of loops:

1. Pretest

– Condition precedes body

– Iterates 0+ times

– This is the most general type of loop

1

Iteration: Intro (2)

2. Posttest

– Condition follows body

– Iterates 1+ times

2

Iteration: Do Loops

• VB has two versions of Do loops:

1. While Boolean expression

– Loops as long as Boolean expression is true

2. Until Boolean expression

– Loops as long as Boolean expression is false

• Both can be used to construct pretest and posttest loops

• Use whichever is easiest in given circumstances

3

Iteration: Pretest Do Loops

• Do loop is pretest if the condition is at the top of the loop (after the Do)

1. Do While

– Syntax:

Do While Boolean expressionstatement(s)

Loop

– Semantics:

4

Iteration: Pretest Do Loops (2)

2. Do Until

– Syntax:

Do Until Boolean expressionstatement(s)

Loop

– Semantics:

5

Iteration: Pretest Do Loops (3)

• Examples:

1. While

’Print limit integers

Dim limit, counter As Integer

limit = txtBox1.Text

counter = 0

Do While counter < limit

lstBox1.Items.Add(CStr(counter))

counter++

Loop

2. Until

’Print limit integers

Dim limit, counter As Integer

limit = txtBox1.Text

counter = 0

Do Until counter = limit

lstBox1.Items.Add(CStr(counter))

counter++

Loop

6

Iteration: Infinite Loops

• Infinite loop: Loop that never terminates

• Result of not updating LCV appropriately

• Example:

’Print limit integers

Dim limit, counter As Integer

limit = 10

counter = 0

Do While counter < limit

lstBox1.Items.Add(CStr(counter))

Loop

7

Iteration: Loop Control

• Main issue with loops is loop control

– Determining how many times the loop body should execute and the tech-niques for controlling this

• 2 general types of loop control:

1. Definite iteration:

– Loop executes a fixed number of times

– This number is known before the loop starts

2. Indefinite iteration:

– Loop executes an indeterminate number of times

8

Iteration: Definite Iteration

• Is an example of count-controlled iteration

– Body will execute a fixed number of times known before the loop starts

• LCV is an example of a variable called a counter

– It counts how many times something occurs

• Example

’count-controlled While loop: Average <limit> integers

Dim limit, counter, sum, number As Integer

limit = 10

counter = 0

sum = 0

Do While counter < limit

number = CInt(txtIn.Text)

counter++

sum += number

Loop

txtOut.Text = "The average = " & sum/limit

• LCV is counter

– Example of a counter-type variable

• Sum is an accumulator variable

– Keeps a total

9

Iteration: Indefinite Iteration

• Used when don’t know ahead of time how many times loop should execute

• 3 types of control:

1. Count-controlled

– Iterations continue until a predetermined number of some occurrencehas been identified

– No knowledge of exactly when this will become true (or false) beforeiteration starts

– Example:

’Count-controlled While loop, indefinite iteration:

’ Average <limit> positive integers

Dim limit, counter, sum, number As Integer

limit = 10

counter = 0

sum = 0

Do While counter < limit

number = CInt(txtIn.Text)

If number > 0 Then

counter++

sum += number

End If

Loop

txtOut.Text = "The average = " & sum/limit

10

Iteration: Indefinite Iteration (2)

2. Sentinel-controlled

– Sentinel is one or more values that signal end of iteration

– Usually outside of range of acceptable values used for processing

– Example:

’Sentinel-controlled While loop: Average positive

’integers. Terminate when a negative is input.

Dim counter, sum, number As Integer

counter = 0

sum = 0

number = CINt(txtIn.Text)

Do While number >= 0

counter++

sum += number

number = CInt(txtIn.Text)

Loop

If counter = 0 Then

txtOut.Text = "no integers were averaged"

else

txtOut.Text = "The average = " & sum/counter

End If

– Requires priming read

∗ Must get initial value for LCV prior to entering loop

11

Iteration: Indefinite Iteration (3)

3. Flag-controlled

– Flag is LCV that keeps track of whether a situation has occurred

– Usually Boolean

– Can be thought of as a specialized sentinel

– Often used when multiple situations are used to terminate loop

12

Iteration: Indefinite Iteration (4)

– Example:

’Flag-controlled Do loop: Average <counter> integers.

’Terminate on a negative or when average > predetermined amount.

’Print the final average and how many integers were involved.

Dim counter, sum, number As Integer

Dim done As Boolean

Dim avg, maxAvg As Single

counter = 0

sum = 0

maxAvg = 50.0

done = False

Do While Not done

number = CInt(txtIn.Text)

If number < 0

done = True

else

counter++

sum += number

avg = sum/counter

If avg >= maxAvg Then

counter--

sum -= number

avg = sum/counter

done = True

End If

End If

Loop

If counter = 0 Then

lstOut.Items.Add("no integers were averaged")

else

lstOut.Items.Add("The average = " & sum/limit)

lstOut.Items.Add("The count = " & counter)

End If

13

Iteration: Post Test Loops

• Body must execute at least once

• Structures

1. Loop Until

– Syntax:

Dostatement(s)

Loop Until Boolean expression

– Semantics:

14

Iteration: Post Test Loops (2)

2. Loop While

– Syntax:

Dostatement(s)

Loop While Boolean expression

– Semantics:

15

Iteration: Post Test Loops (3)

• Examples:

1. Until

’Loop Until for input verification

Dim option As Integer

Do

option = InputBox("Enter a number between 5 and 10 ")

If ((option < 5) Or (option > 10)) Then

MsgBox("***Not a valid number***")

End If

Loop Until (option > 4 And option < 11)

2. While

’Loop While for input verification

Dim option As Integer

Do

option = InputBox("Enter a number between 5 and 10 ")

If ((option < 5) Or (option > 10)) Then

MsgBox("***Not a valid number***")

End If

Loop While (option < 5 And option > 10)

16

Iteration: Exit Do

• The Exit Do statement immediately exits a Do statement when executed

– It halts iteration

– It can make some coding less awkward

• Consider an earlier example:

Dim counter, sum, number As Integer

Dim done As Boolean

Dim avg, maxAvg As Single

counter = 0

sum = 0

maxAvg = 50.0

done = False

Do While Not done

number = CInt(txtIn.Text)

If number < 0

done = True

else

counter++

sum += number

avg = sum/counter

If avg >= maxAvg Then

counter--

sum -= number

avg = sum/counter

done = True

End If

End If

Loop

If counter = 0 Then

lstOut.Items.Add("no integers were averaged")

else

lstOut.Items.Add("The average = " & sum/limit)

lstOut.Items.Add("The count = " & counter)

End If

17

Iteration: Exit Do (2)

• Consider the same example using Exit Do

Dim counter, sum, number As Integer

Dim avg, maxAvg As Single

counter = 0

sum = 0

maxAvg = 50.0

Do While True

number = CInt(txtIn.Text)

If number < 0

Exit Do

else

counter++

sum += number

avg = sum/counter

If avg >= maxAvg Then

counter--

sum -= number

avg = sum/counter

Exit Do

End If

End If

Loop

If counter = 0 Then

lstOut.Items.Add("no integers were averaged")

else

lstOut.Items.Add("The average = " & sum/limit)

lstOut.Items.Add("The count = " & counter)

End If

18

Iteration: Nested Loops

• Can place one loop inside of another

• Must make sure that initializations and updates occur for each loop and in theappropriate places

• Example:

’Nested Do loops: Print times tables.

Dim n, counter1, counter2, product As Integer

n = 5

counter1 = 1

Do While counter1 <= n

lstOut.Items.Add("" & counter1 & "’s times table: "

counter2 = 1

Do While counter2 <= 9

product = counter1 * counter2

lstOut.Items.Add_

("" & counter1 & " x " & counter2 & " = " & product)

counter2++

Loop

counter1++

Loop

19

Iteration: For-Next Loops

• Special loop form

• Works same as Do While

• Loop control handled automatically in header

• Syntax:

For LCV As type = initial expression To final expression Step deltastatement(s)

Next

• Semantics:

LCV = initial_expression

Do While Math.abs(LCV - final_expression) > 0

statement(s)

LCV += delta

Loop

• The Step option

– Step is optional

∗ If Step omitted, delta = 1

– If Step not of type Integer, must be of type Double

• Example:

’count-controlled For-Next loop: Average <limit> integers

Dim limit, sum, number As Integer

limit = 10

sum = 0

For counter As Integer = 1 To limit

number = CInt(txtIn.Text)

sum += number

Next

txtOut.Text = "The average = " & sum/limit

20

Iteration: For-Next Loops

• Example:

’count-controlled For-Next loop: Counting backwards by 2’s

Dim limit, As Integer

limit = CInt(txtIn.Text)

If limit < 0 Then

limit = -limit

End If

If limit < 2 Then

limit = 2

End If

For counter As Integer = limit To 0 Step -2

lstOut.Items.Add(counter)

Next

• Example:

’count-controlled For-Next loop: Counting tenths

Dim limit As Integer

limit = CInt(txtIn.Text)

If limit < 0 Then

limit = -limit

End If

For counter As Double = 0 To limit Step 0.2

lstOut.Items.Add(counter)

Next

• The type declaration in the header is oprional

– It is generally preferrable to declaring the ]em LCV outside of the loop

– When declared in the header, the variable is local to the loop

∗ It cannot be used outside of the loop

21


Recommended