Upload
seth
View
16
Download
0
Tags:
Embed Size (px)
DESCRIPTION
- PowerPoint PPT Presentation
Citation preview
1
INF110Visual Basic Programming
AUBG Spring semester 2011
Reference books:Schneider D., An Introduction to Programming Using Visual Basic, Prentice Hall, Pearson Education Inc., 7th Ed. 2008, 6th Ed. 2006 Liberty J., Learning Visual Basic .NET, O’Reilly, 2002 Any Visual Basic book available in AUBG library
Course lecturer: Assoc. Prof. Svetla Boytcheva, PhD
2
INF110 Visual Basic Programming AUBG Spring semester 2011
Lecture 7Title:
Visual Basic(Repetition/Iteration
statements 1)
3
Lecture Contents:
Repetition/Iteration statements:Pre Test LoopsPost Test LoopsLogically Controlled LoopsCounter Controlled LoopsNested Loops
4
Quiz 2on
Decision Operators and Expressions
5
Control Structures IIControl Structures II
RepetitionRepetition
(aka Iteration)(aka Iteration)
INF110
Visual Basic Programming
6
An iterative statement is one which executes one or more other statements a certain number of times
i.e. the execution of one or more statements is repeated
The iterative statement comes in a variety of “flavours”.
They are used for a number of purposes, such as:• searching a collection of data items for one with a specific value, or• performing a calculation involving a collection of data items (e.g. adding them all together to get a total) or• performing some action repeatedly until an event occurs which tells it to stop (imagine a robot placing boxes on a conveyor belt ...)
7
• Repetition statements (also iterative statements) may classify in two sub groups:
Do…Loop statements
For…Next statements
8
Do Loops
• A loop is one of the most important structures in programming.
• Used to repeat a sequence of statements a number of times.
• The Do loop repeats a sequence of statements either:• as long as, a certain condition is True.• until, a certain condition becomes True.
• It has a few variants …
9
Comments
• Be careful to avoid infinite loops – loops that never end.
• VB.NET allows for the use of either the While keyword or the Until keyword at the top or the bottom of a loop. We will mostly use While at the top of a loop (pretest loop) and Until at the bottom of a loop (posttest loop).
• Semantics:
“Do these actions while condition is true”
or
“Do these actions until a condition becomes true”
10
•Variations of the Do…Loop control structure:
Do … Loop1/ Pre test loops
with While and Until
2/ Post test loops
with While and Until
11
Do LoopsDo While boolean expression
statementsLoop------------------------------------------Do Until boolean expression
statementsLoop------------------------------------------Do
statementsLoop While boolean expression------------------------------------------Do
statementsLoop Until boolean expression------------------------------------------Do
statementsLoop
12
Do Loops in VBasic
Pretest loops
----------------------------------------- Do While boolean expressionstatements
Loop-----------------------------------------Do Until boolean expressionstatements
Loop-----------------------------------------
13
Do Loops in VBasic
Posttest loops
-----------------------------------------Do statements
Loop While boolean expression-----------------------------------------Do statements
Loop Until boolean expression-----------------------------------------
14
Do Loops in VBasic
Infinite /endless/ loops
-----------------------------------------Do statements
Loop -----------------------------------------
15
Do While <condition> … Loop
Statement
16
Do While … Loop Syntax
Do While condition
statement(s)
Loop
Condition is tested.If it is True,
the loop is run.If it is False,
the statements following the Loop statementare executed.
These statements are inside the body of the loop and are run if the condition
above is True.
condition is a Boolean expression
17
Pseudocode and Flow Chart for a Do Loop
18
Dim Counter As Integer = 20Do While Counter <= 100
Console.Writeline(Counter)
Counter = Counter + 10
Loop
The above example will keep on adding until Counter’s value becomes > 100
19
Example
Dim PassWord As String
PassWord = “”
Do While PassWord <> “SHAZAM”
Console.Writeline(“Enter password:")
PassWord = Console.Readline()
Loop
PassWord is the loop control variable because the value stored in PassWord
is what is tested to determine if the loop should continue or stop.
20
‘Accumulate sum of the numbers from 1 to 7
Dim Num As Integer = 1 Dim Sum As Integer = 0
Do While Num <= 7 Sum = Sum + Num Num = Num + 1 'Add 1 to the value of Num Loop
21
Do … Loop Until <condition>
Statement
22
Do … Loop Until
Do
statement(s)
Loop Until condition
Loop is executed once and then the conditionis tested. If it is False, the loop is run again.
If it is True, the statements following the Loop statement are executed.
Since the condition is tested at thebottom the loop, the loop will
execute at least once.
23
Pseudocode and Flowchart for a Do … Loop Until
24
Dim Counter As Integer = 20
Do Console.Writeline(Counter) Counter = Counter + 10
Loop Until Counter > 100
25
Example
Dim PassWord As String
Do
Console.Writeline(“Enter password:")
PassWord = Console.Readline()
Loop Until PassWord = "SHAZAM"
26
Nested Loops
Statements inside a loop can contain another loop.
(Just like If statements).
Example: What is the output of this code?i = 0
Do While i < 6
j = 0
Do While j < 6
Console.Write("*")
j = j + 1
Loop
Console.WriteLine()
i = i + 1
Loop
Nested loops are quite common, especially for processing tables of data.
Assume initially that i = 0
27
Nested Loops
Statements inside a loop can contain another loop.
(Just like If statements).
Example: What is the output of this code?i = 0
Do While i < 6
j = 0
Do While j < i
Console.Write("*")
j = j + 1
Loop
Console.WriteLine()
i = i + 1
Loop
Nested loops are quite common, especially for processing tables of data.
Assume initially that i = 0
28
When condition is a variable of Boolean type,
the statements likeIf flagVar = True Then ...
can be replaced byIf flagVar Then ...
and
the statements likeIf flagVar = False Then ...
can be replaced byIf Not flagVar Then ...
29
The statements like
Do While flagVar = True
can be replaced by
Do While flagVar
and
The statements like
Do While flagVar = False
can be replaced by
Do While Not flagVar
30
The iterative statement
Do While condition
statement(s)
Loop
Has an alternative while control structure:
The While repetition structure
31
While Repetition Structure
• Repetition structure
– Allows the programmer to specify that an action should be repeated, depending on the value of a condition.
• Example (pseudocode)
While there are more items on my shopping list
Purchase next item
Cross it off my list
Just like Do While ... loop
32
Dim Product As Integer = 2 While Product <= 1000
Console.Writeline(Product)Product = Product * 2
End While
The decision is tested each time the loop iterates
product <= 1000
true
product = product * 2
false
33
‘ Modern VB 2005/2008 versionDim Product As Integer = 2While Product <= 1000
Console.Writeline(Product)Product = Product * 2
End While
VB6 >>> VB 2005/2008The End While statement replaces the Wend statement of VB6.
‘ Obsolete VB 6 versionDim Product As Integer = 2While Product <= 1000
Console.Writeline(Product)Product = Product * 2
WEnd
34
Nested Loops using While … End While control structure
Statements inside a loop can contain another loop.
Example: What is the output of this code?
i=0
While i < 6
j = 0
While j < 6
Console.Write("*")
j = j + 1
End While
Console.WriteLine()
i = i + 1
End While
Nested loops are quite common, especially for processing tables of data.
Assume initially that i = 0
35
Nested Loops using While … End While control structure
Statements inside a loop can contain another loop.
Example: What is the output of this code? i=0
While i < 6
j = 0
While j < i
Console.Write("*")
j = j + 1
End While
Console.WriteLine()
i = i + 1
End While
Nested loops are quite common, especially for processing tables of data.
Assume initially that i = 0
36
Do Loops• All the variations use the same basic model.
A pretest loop is executed either– While the condition is True. Uses While
reserved wordDo While conditionstatement-block
Loop
– Until the condition becomes True. Uses Until reserved wordDo Until conditionstatement-block
Loop
37
Examples
I = 1
Do While (I <= 10)
Console.WriteLine(I)
I = I + 1
Loop
How many iterations are to be run? (10) Try it
38
Examples
I = 1
Do Until I <= 10
Console.WriteLine(I)
I = I + 1
Loop
How many iterations are to be run? (0) Try it
39
Examples to achieve the same effectI = 1Do While (I <= 10)
Console.WriteLine(I)I = I + 1
Loop======================= same effectI = 1Do Until Not(I <= 10)
Console.WriteLine(I)I = I + 1
Loop
How many iterations are to be run? (10) Try it
40
Examples to achieve the same effectI = 1Do While Not(I <= 10)
Console.WriteLine(I)I = I + 1
Loop======================= same effectI = 1Do Until (I <= 10)
Console.WriteLine(I)I = I + 1
Loop
How many iterations are to be run? (0) Try it
41
Post test loops with While and Until
42
Do Loops• All the variations use the same basic model.
A posttest loop is executed either– While the condition is True. Uses While
reserved wordDostatement-block
Loop While condition
– Until the condition becomes True. Uses Until reserved wordDostatement-block
Loop Until condition
43
Examples
I = 1
Do
Console.WriteLine(I)
I = I + 1
Loop While (I <= 10)
How many iterations are to be run? (10) Try it
44
Examples
I = 1
Do
Console.WriteLine(I)
I = I + 1
Loop Until (I <= 10)
How many iterations are to be run? (1) Try it
45
Examples to achieve the same effect
I = 1Do
Console.WriteLine(I)I = I + 1
Loop While (I <= 10)=================== same effectI = 1Do
Console.WriteLine(I)I = I + 1
Loop Until Not(I <= 10)
How many iterations are to be run? (10) Try it
46
Examples to achieve the same effect
I = 1Do
Console.WriteLine(I)I = I + 1
Loop While Not(I <= 10)=================== same effectI = 1Do
Console.WriteLine(I)I = I + 1
Loop Until (I <= 10)
How many iterations are to be run? (1) Try it
47
Endless loops
with While … End While
andDo … Loop
48
Endless loops - examples
While True
statement-block
End While
49
Endless loops - comments
The endless loops should be avoided. They must be terminated from within the own loop body with an Exit statement
While True statement-block
if condition Then Exit Whilestatement-block
End While
50
Endless loops - examples
Do
statement-block
Loop
51
Endless loops - comments
The endless loops should be avoided. They must be terminated from within the own loop body with an Exit statement
Dostatement-blockIf condition Then Exit Dostatement-block
Loop
52
From Logically controlled loop
ToCounter controlled loop
Introduction to
For … Next Loop statement
53
You use a Do loop when you do not know how many times the statements should be run.
If you know that they should be run for a specific
number of times, then use a For … Next loop.- coming on next slides!
This loop variant uses a counter which increases or decreases on each repetition of the loop and the looping ends when this counter reaches a set value.
54
For … Next Loops
• Used when we know how many times we want the loop to execute.
• A counter-controlled loop
55
For … Next Loop Syntax
The format is:
For counter = startNumber To endNumber Step increment
One or more VB statements
Next
starts with counter = startNumber and increments counter each time through the loop by an amount equal to increment until it reaches endNumber.
The bounds (startNumber, endNumber) are integer quantities, and Step controls the increments (which may be negative).
56
For … Next Loop Syntax
One more format is:
For counter = startNumber To endNumber [Step increment]
One or more VB statements
Next [counter]
The brackets [ … ] are meta characters and indicate that the keywords in the square brackets are optional.
57
For index = 0 To n Step s
...
Next
Controlvariable
Startvalue
Stopvalue
Amountto add to
index
58
For … Next Loop Syntax
The most common use of the FOR loop omits Step increment – the default increment is +1, i.e. the counter is increased by 1 each time through the loop.
59
Sample
For i = 1 To 5
...
Next
The loop control variable (i.e. counter), i, is – Initialized to 1– Tested against the stop value, 5– Incremented by 1 at the Next statement
60
For i = 1 To 5 [Step 1] ...Next
And its corresponding Do While equivalent
i = 1
Do While i <= 5
...
i = i + 1
Loop
61
(a) For counter=1 to 10
Console.Writeline(counter)
Next
(b) For counter=1 to 100 Step 10
Console.Writeline(counter)
Next
(c) For counter=100 to 5 Step -5
Console.Writeline(counter)
Next
Examples
62
For Num = 1 To 10 NumSquared = Num*Num Console.Writeline(NumSquared) Next Num
The statements between the "For Num = 1 To 10" line and the "Next Num" line are executed ten times.The first time, the variable Num contains the value 1.The second time, Num contains the value 2, the third time, 3, and so on.On the tenth time around (the tenth "iteration") num contains the value 10.After that there are no further iterations - the computer moves on to the line following the "Next num" line.
63
Start, Stop, and Step values
• Consider a loop beginning with
For i = m To n Step s
• The loop will be executed exactly once if m equals n no matter what value s has.
• The loop will not be executed at all if m is greater than n and s is positive.
• The loop will not be executed at all if m is less than n and s is negative.
64
Altering the Control Variable
• The value of the control variable should not be altered within the body of the loop• Doing so might cause the loop to repeat
indefinitely • Or have an unpredictable number of
repetitions.
• The value of the control variable should not be referenced after the Next statement
65
Altering the Control Variable
For I = 0 to 10
Console.WriteLine(i)
I = I – 1
Next I
This is a loop that never ends. Why?
66
Altering the Stop Value
The stop value may be specified as literal For I = 0 to 10
The stop value may be specified as constant Const MyConst As Integer = 10
For I = 0 to MyConst
The stop value may be specified as variable Dim endValue As Integer
endValue = 10
For I = 0 to endValue
67
Altering the Stop Value
Attention: keep in mind when working with For…Next loops that the stop value is set at the beginning of the loop. Changing the value of the EnDVariable in the loop’s body won’t have any effect.
For example, The following loop will execute 11 times, not 51
Dim endValue As Integer = 10
For I = 0 to endValue
endValue = 50
Console.WriteLine(endValue)
Next I
68
Non-integer Step Values
• Can lead to round-off errors with the result that the loop is not executed the intended number of times.
• The loop counter should be Integer.
69
Non-integer Step Example
• A loop beginning with
For i = 1 To 2 Step 0.1
will be executed only 10 times instead of the intended 11 times.
It should be replaced with
For i = 1 To 2.01 Step 0.1
70
Nested For … Next Loops
71
Questions?Questions?
72
Thank You For
Your Attention!