IT - Looping
IT - Looping
Repetition / Looping
Information Technology IIA
Lecture 05
By D.P Kalansuriya
1
12/15/2020
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
2
12/15/2020
• 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
Do While Examples
Dim counter As Integer
counter = 1
Do While counter <= 3
Print counter
counter = counter + 1
Loop
3
12/15/2020
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
• counter increases by one for each repetition
• Finally (counter <= 3) 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 counter from the previous example
• Counters are typically initialized before the loop begins
counter = 1
• The counter is then modified in the body of the loop
counter = counter + 1
4
12/15/2020
True
5
12/15/2020
• 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
Do Until Examples
Dim counter As Integer
counter = 3
Do
Print counter
counter = counter + 1
Loop Until counter > 3
6
12/15/2020
7
12/15/2020
EndValue is exceeded
True
• 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
8
12/15/2020
9
12/15/2020
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
10
12/15/2020
Nested Examples
Dim i, j As Integer
For i = 0 To 5
For j = 0 To 3
Print "*";
Next
Print '\n'
Next
11