Vous êtes sur la page 1sur 11

LESSON 10

REPETITION STRUCTURE
LOOPS
A LOOP is a set of instructions that are executed several
times. Loops play important roles in programs because you'll need
to repeat sections of a program to process multiple data values. For
example, you might need to calculate a total of past due charges for
all past due customers. A loop can read each customer's past due
charge and add that amount to the running total. As you learn more
about Visual asic in subse!uent lessons, you "ill see additional
uses for loops. Visual asic provides four main #inds of loops$ the
classic %o&Loop, the %o&'ntil Loop, the %o&(hile Loop, and the For&
)ext Loop.
Do-Loops
*he most basic form of loop in Visual asic is the %o&Loop.
FORMAT:
%o
+,ode to execute-
Loop
*his, !uite simply, executes the bloc# of code, and "hen it reaches
Loop, returns to the beginning of the %o Loop and executes the
same bloc# of code again. *he same bloc# of code "ill be repeatedly
executed until it is told to stop executing. .o let's try to apply this
to our problem of generating the Fibonacci series$
Example: Fibonacci Series
%im / As 0nteger
%im 1 As 0nteger

%o
%ebug.Print /

/ 2 1 3 /
1 2 / & 1
Loop

And, believe it or not, this code "or#s4 (ell, sorta. 0f you try
to run this code, it "ill indeed generate the Fibonacci series5
ho"ever, it "ill continually generate and print out the next number
infinitely&&or, in this case, until it reaches an overflo" error. *his is
#no"n as the problem of the infinite do&loop, one that all
programmers "ill experience, and some !uite fre!uently.
Exit Do
.o "e clearly need some "ay to escape from the %o&Loop.
1ou could, of course, simply 6nd the program once you have
calculated enough values, but "hat if you still need to perform tas#s
after you're done calculating7 *he ans"er is to use the 6xit %o
statement. (henever your program reaches an 6xit %o statement
"ithin a loop, it "ill exit the current loop. .o, let's try a some"hat
different approach to the Fibonacci problem. (e decide that "e
"ant to calculate only eight values of the Fibonacci series, so "e'll
#eep a counter and increment it each time throughout the loop.
*hen, once the counter reaches eight, "e'll exit the loop.
Example: Fibonacci series
Public .ub 8ain+-
%im / As 0nteger
%im 1 As 0nteger
%im cnt As 0nteger 'Our counter.
cnt 2 9
%o
%ebug.Print /
/ 2 1 3 /
1 2 / & 1

0f cnt :2 ; *hen
6xit %o
6lse
cnt 2 cnt 3 9
6nd 0f
Loop
6nd .ub
*his program successfully computes and prints out the first
eight values of the Fibonacci series.
The Do While Loops
*he %o (hile loop is perhaps the most common looping
statement that you'll put in Visual asic programs. %o (hile "or#s
"ith comparison expressions <ust as the 0f statement does.
*herefore, the six comparison operators that you learned about in
the previous lesson "or# as expected here. =ather than controlling
the one&time execution of a single bloc# of code, ho"ever, the
comparison expression controls the looping statements. Li#e the 0f
statement that ends "ith an 6nd 0f statement, a loop "ill al"ays be
a multiline statement that includes an obvious beginning and ending
of the loop.
Format:
%o (hile +6xpression-
+,ode to execute-
Loop
+6xpression- can be any legal logical expression that "e "ish to
evaluate to determine "hether or not to exit the loop. *he bloc# of
code continues looping as long as comparison test is true. (hether
you insert one or several lines of code for the bloc# doesn't matter.
0t's vital, ho"ever, for the bloc# of code to someho" change a
variable used in comparison test. *he bloc# of code #eeps repeating
as long as the %o (hile loop's comparison test continues to stay
true. 6ventually, comparison test must become false or your
program "ill enter an infinite loop and the user "ill have to brea#
the program's execution through an inelegant means, such as
pressing the ,trl3rea# #ey combination. *he %o (hile loop
continues executing a bloc# of Visual asic statements as long as
comparison test is true. As soon as comparison test becomes false,
the loop terminates, thus it "ill give us an infinite loop. An infinite
loop is a loop that never terminates. elo" is an example Fibonacci
program using the %o (hile loop.
Example: Fibonacci series using Do-while loop
Public .ub 8ain+-
%im / As 0nteger
%im 1 As 0nteger
%im cnt As 0nteger 'Our counter.

cnt 2 9
%o (hile cnt > ;
%ebug.Print /
/ 2 1 3 /
1 2 / & 1

cnt 2 cnt 3 9
Loop
6nd .ub
CAT!O"
Guard against infinite loops and always make sure that your
loops can terminate properly. Even if you provide an Exit command
button or a File | Exit menu option in your application, the program
will often ignore the user's exit command if the program enters an
infinite loop.
The Do Until Loop
(hereas the %o (hile loop continues executing the body of
the loop as long as the comparison test is true, the %o 'ntil loop
executes the body of the loop as long as the comparison test is
false. *he program's logic at the time of the loop determines "hich
#ind of loop "or#s best in a given situation.
Format:
%o 'ntil +6xpression-
+,ode to execute-
Loop
%o 'ntil "or#s almost exactly li#e the %o (hile loop except
that the %o 'ntil loop continues executing the body of the loop until
the comparison test is true. +6xpression- can be any legal logical
expression that "e "ish to evaluate to determine "hether or not to
exit the loop. 6ach time the program reaches Loop it "ill evaluate
this expression. 0f the expression is *rue, it "ill exit the loop for us,
but other"ise it "ill continue looping. elo" is an example Fibonacci
program using the %o 'ntil loop.
Example: Fibonacci series using Do-until loop
Public .ub 8ain+-
%im / As 0nteger
%im 1 As 0nteger
%im cnt As 0nteger 'Our counter.

cnt 2 9

%o 'ntil cnt :2 ;
%ebug.Print /

/ 2 1 3 /
1 2 / & 1
cnt 2 cnt 3 9
Loop
6nd .ub
T!#
emember that the comparison test must be false for the loop to
continue.
Which Loop Is Best?
'se the loop that ma#es for the cleanest and clearest
comparison test . .ometimes, the logic ma#es the %o (hile clearer,
"hereas other loops seem to "or# better "hen you set them up
"ith %o 'ntil.
%o 'ntil continues executing a bloc# of Visual asic
statements as long as comparison test is false. As soon as
comparison test becomes true +the loop is said to %o a loop until
the condition becomes false-, the loop terminates and the program
continues on the line that follo"s the closing loop statement.
*here is really no technical advantage to using %o (hile
instead of %o 'ntil. 'se "hichever one seems to flo" the best for
any given application.
The For Loop
0n situations "here you merely "ant to run the loop a
predefined number of times, it can become !uite tiresome to have
to create and manage a counter for each loop, "hich is "hy "e also
have something called a For&)ext Loop. 'nli#e the %o loops,
ho"ever, the For loop repeats for a specified number of times. *he
format of the For loop loo#s a little more daunting than that of the
%o loops, but after you master the format, you'll have little trouble
implementing For&)ext Loop "hen your code needs to repeat a
section of code for a specified number of times. *here isn't one
correct loop to use in all situations. A For&)ext Loop al"ays begins
"ith the For statement and ends "ith the )ext statement.
Format:
%im 0 As 0nteger

For 0 2 +0nteger- *o +0nteger-
+,ode to execute-
)ext 0
(e used the variable name ?0? above, as it is the most
common name used for For&Loops5 ho"ever, you can use any
variable name you "ant, so long as the variable is of the type
0nteger. elo" is an example Fibonacci program using the For&)ext
Loop.
Example: Fibonacci series using For-"ext loop
Public .ub 8ain+-
%im / As 0nteger
%im 1 As 0nteger
%im cnt As 0nteger 'Our counter.

For cnt 2 9 *o ;
%ebug.Print /
/ 2 1 3 /
1 2 / & 1
Loop
6nd .ub
0n the example above, "e first dimensioned cnt as an
0nteger, and then, in the declaration of the For&)ext loop, set its
value to 9. 6ach time through the loop, the value of cnt "as
incremented by 9 until it reached ;, at "hich point the loop "as
executed.
Exit For
As "ith %o Loops, there is a statement that can be used to exit a
For&)ext loop, and it is called 6xit For. .imply invo#e this statement
any"here "ithin a For&)ext loop and the current loop "ill be exited.
Step
y default, the variable used in the declaration of the For&)ext loop
is incremented by 9 each time through the loop5 ho"ever, if you
"ant to increment this value by a different amount each time
through the loop, you can simply append .tep +0nteger- to the end
of the For&)ext loop declaration. 0f, for instance, "e "anted to print
out every even number counting bac#"ard from @A to A, "e could
do this using the follo"ing code$
%im 0 As 0nteger

For 0 2 @A *o A .tep &@
%ebug.Print 0
)ext 0
.o there you have it no" you can use loops all over your Visual
asic B programs. *hese are one of the most useful tools you have.
You Can Terinate Loops Earl!
.ometimes, you'll be processing user input or several data
values using looping statements, and an exception occurs in the
data that re!uires an immediate termination of the loop. *he 6xit
%o and the 6xit For statements automatically terminate loops. )o
matter "hat the %o loop's comparison test results in, or ho" many
more iterations are left in a For loop, "hen Visual asic encounters
an 6xit %o or 6xit For statement, it immediately !uits the loop and
sends execution do"n to the statement follo"ing the loop. Visual
asic also supports the 6xit .ub statement that terminates a
procedure early.
"ote
!t is not recommend that you rely on the Exit statement to bail out
of control blocks and procedures. "ost experienced programmers
will not use the exit function. #he Exit statement has a nasty habit
of creating multiple exit points for a block of code, which normally
makes the code harder to understand and maintain.
Test Your Knowledge
9- 0t is a set of instructions that are executed several times.
a. %eclarations
b. Loop
c. %ata type
d. ,ontrol
@- 6numerate the four main #inds of Visual asic loops
a. CCCCCCCCC
b. CCCCCCCCC
c. CCCCCCCCC
d. CCCCCCCCC
D- 6xplain briefly the four main #inds of Visual asic Loops.
E- (hat #ey"ord is used to terminate a loop7
a. 6xit
b. *erminate
c. ,lose
d. Loop6xit
F- Go" important is terminating a loop properly7 6xplain briefly.

Vous aimerez peut-être aussi