Sei sulla pagina 1di 16

Introduction

Generally a program executes its statements from the beginning to end. Most programs decide
what to do in response to changing circumstances. These programs not only store data but they
also manipulate data in terms of consolidation, rearranging, modifying data. To perform their
manipulative miracles, program need tolls for performing repetitive actions and for making
decisions. Visual Basic provides such tools by providing different statements to do so. uch
statements are called program control statements. This chapter discusses such statements in detail
like !f "#ndif , elect $ase, %o&'oop, (or ) *ext and +hile&+end.
Control Flow Statements/Control Structures
(low is the term used for the order that the computer executes the lines of code in our programs.
The simplest flow executes one line of code after the other. $ontrol structures are the structures
that control the flow of program,s execution. !n #very programming language, statements may
be executed se-uentially, selectively or iteratively. There are three basic structures to control the
order of execution in a program.
.. Sequence: The sequence construct means the statements are being executed sequentially. This
is the natural or default flow of statement (see fig ).
Example: see fig
Fig The sequence construct
2. Selection/Branching: The selection construct means the execution of statement(s) depending
upon a conditiontest. !f a condition e"aluates to true# a set of statements is followed# otherwise
another set of statements is followed. This construct (selection construct) is also called decision
construct because it helps in ma$ing decision about which set of statements is to be executed.
There are two categories of selection constructs: conditional and unconditional.
tatement ./
0rint 1+elcome to VB2
tatement 3/
0rint 1This is e-uential flow2
tatement 4/
*um5.66
tatement 7/
0rint num
The following illustration shows a decision structure that tests for a condition being true and
takes different actions depending on whether it is true or false.
Taking different actions when a condition is true and when it is false
3. Iteration: The iteration constructs means repletion of a set of statements depending
upon a condition. A set of statements are repeated again and again till the condition
or Boolean expression is true (or false). As soon as the condition becomes false (or
true), the repetition stops. The iteration constructs is also called looping constructs.
The following figure illustrates the iteration construct.
$ondition
8
tatement . tatement 3
tatement 3
tatement .
One course-of-action
Another
course-
of-action
true
false
The set of statements that are repeated again and again is called the body of the loop. The
condition on which the execution of the loop depends is called test condition or the condition
on which the exit from the loop depends is called exit condition.
!ery programming language must pro!ide all these constructs as the default mode of
execution (se"uential) is inade"uate to sol!e most of the problems. #isual Basic also
pro!ides statements that support these construct.
Decision Structures (Selection Constructs)
$ecision structures or selection statements allow us to select the set of instructions for
execution depending on the test condition. %e can choose to execute one of se!eral
different blocks of statements, depending on the !alue of an expression. This process is
known as selection. &r, we can choose one of two different paths, depending on the
outcome of logical expression (true or false).This process in known as branching. #isual
Basic pro!ides two categories of branching commands.
i. 'onditional branching
ii. (nconditional branching
#isual Basic allows you to test conditions and perform different operations depending on the
results of that test. )ou can test for a condition being true or false, for !arious !alues of an
expression, or for !arious exceptions generated when you execute a series of statements.
#isual Basic pro!ides !arious conditional statements are*
The loop
body
tatement 3
tatement .
The exit condition
True
$ondition
8
a. The +f.. Then statement
b. The +f,Then, lse statement
c. The +f,Then, lse+f statement
d. -ested +f statement
e. The .elect 'ase statement
%et us learn about these one by one
a. !f...Then statement
The !f...Then selection structure tests the conditions specified and if it is True# executes the statements
that follows. !f the condition is False then it continues with the statement. The !f statement can ha"e single
line or multiple line syntax.
Single line statement: To execute one statement conditionally# the single line syntax is:
!f &'oolean expression( Then statement
+here
$ondition may be any valid function or expression that returns a True or (alse value.
tatement represents the task to be performed if the condition is True, which can be any valid VB
statement including a procedure call, nested conditions and loops.
Example: !f dob)*+2,+2,-.* then /sgbox 0This is 1ate of 'irth*
Multiple line statement:
The syntax of the If...Then selection
If <Boolean expression> Then
statements
End If
If the expression evaluates to true, the statements are executed, otherwise
ignored.
e.g.: If average>6 Then
txt!rade.Text " #$#
End If
In the a%ove example, if the value of varia%le average is greater than 6 then
grade &$' is displa(ed in the txtgrade text%ox. )therwise, the flow *umps to
End If statement
+ou can also execute multiple statements %( separating them with a colon:
!f &'oolean expression( Then statement+: statement2: statement2
!f there is a single statement use the single line syntax. !n the case of many statements use multiple line
syntax. Terminate the conditional statement with End !f.
b. !f...Then...Else selection structure
This is an extension to the simple !f 3Then statement. The If...Then...Else selection structure
allows the programmer to specify that a different action is to be performed when the condition is True than
when the condition is False.
4yntax of the If...Then...Else selection
If <condition > Then
statements
Else
statements
End If
e.g.: If average>, Then
txt!rade.Text " #-ass#
Else
txt!rade.Text " #.ail#
End If
5ested !f...Then...Else selection structure
5ested If...Then...Else selection structures test for multiple cases by placing
If...Then...Else selection structures inside If...Then...Else structures.
4yntax of the 5ested If...Then...Else selection structure
6ou can use 5ested !f either of the methods as shown abo"e
Method 1
If < condition / > Then
statements
ElseIf < condition 0 > Then
statements
ElseIf < condition 1 > Then
statements
Else
2tatements
End If
Method 2
If < condition / > Then
statements
Else
If < condition 0 > Then
statements
Else
If < condition 1 > Then
statements
Else
2tatements
End If
End If
EndIf
e.g.: 7ssume you ha"e to find the grade using nested if and display in a text box
If average > 3, Then
txt!rade.Text " #$#
ElseIf average > 6, Then
txt!rade.Text " #B#
ElseIf average > ,, Then
txt!rade.text " #4#
ElseIf average > 5, Then
txt!rade.Text " #2#
Else
txt!rade.Text " #.#
End If
The Case Structure

8hen the situation arises where you need to choose between more than two
alternati"es# an extended form of the selection structure# called the case structure# must
be used. 7 flowcharted example follows:
!n 9'# the case structure can be implemented in one of two ways: with an extended
bloc$ !f structure# or with the 4elect :ase statement structure.
The expression list in a ;:ase; clause can ha"e any of the following formats:

(ormat #xamples
9expression: ;, expression, . . . <
4ase /, /, /
4ase #+#, #(#
9expression: To 9expression:
4ase / To 6
4ase #$# To #4#
!s 9relational operator expression:
4ase Is >" 0/
=combination of any of the above>
4ase Is <" ,, 0 To 06, 51

The 4elect :ase statement does not need to be ;tied; to one particular "ariable or expression< it can be
used to e"aluate any number of conditions# using the following format:

2elect 4ase True
4ase <condition />
<2tatement list />
4ase < condition 0>
<2tatement list 0>
4ase Else
<2tatement list n>
End 2elect
.elect case statement
/uns one of se!eral groups of statements, depending on the !alue of an expression.
Select [ Case ] testexpression
[ Case expressionlist
[ statements ] ]
[ Case Else
[ elsestatements ] ]
End Select
Parts
testexpression
/e"uired. xpression. 0ust e!aluate to one of the elementary data types
(Boolean, Byte, Char, Date, Double, Decimal, Integer, ong,!b"ect, SByte, S
hort, Single, String, #Integer, #ong, and #Short).
expressionlist
/e"uired in a Case statement. 1ist of expression clauses representing match !alues
for testexpression. 0ultiple expression clauses are separated by commas. ach
clause can take one of the following forms*
expression1 To expression2
2 Is 3 comparisonoperator expression
expression
(se the To keyword to specify the boundaries of a range of match !alues
for testexpression. The !alue of expression1 must be less than or e"ual to the !alue
of expression2.
(se the Is keyword with a comparison operator ($, %&, %, %$, &, or &$) to
specify a restriction on the match !alues for testexpression. +f theIs keyword is not
supplied, it is automatically inserted before comparisonoperator.
The form specifying only expression is treated as a special case of the Is form
where comparisonoperator is the e"ual sign ($). This form is e!aluated
as testexpression 4 expression.
The expressions in expressionlist can be of any data type, pro!ided they are
implicitly con!ertible to the type of testexpression and the
appropriate comparisonoperator is !alid for the two types it is being used with.
statements
&ptional. &ne or more statements following Case that run if testexpression matches
any clause in expressionlist.
elsestatements
&ptional. &ne or more statements following Case 'lse that run
if testexpression does not match any clause in the expressionlist of any of
theCase statements.
'nd Select
Terminates the definition of the Select...Case construction.
4elect...:ase selection structure
2elect...4ase structure is an alternati"e to If...Then...ElseIf for selecti"ely executing a
single bloc$ of statements from among multiple bloc$ of statements. 2elect...case is more
con"enient to use than the If...Else...End If. The following program bloc$ illustrate the wor$ing
of 2elect...4ase.
4yntax of the 2elect...4ase selection structure
2elect 4ase Index
4ase
2tatements
4ase /
2tatements
End 2elect
e.g.: 7ssume you ha"e to find the grade using select...case and display in the text box
7im average as Integer
average " txt$verage.Text
2elect 4ase average
4ase / To 3,
txt!rade.Text "#$#
4ase 35 To 6,
txt!rade.Text "#B#
4ase 65 To ,,
txt!rade.Text "#4#
4ase ,5 To 5,
txt!rade.Text "#2#
4ase 55 To
txt!rade.Text "#.#
4ase Else
8sgBox #Invalid average mar9s#
End 2elect
1oops pro!ide the ability to repeatedly execute the same block of code, and to each time change
!alues such that each run through the loop produces different results. #isual Basic pro!ides four main
kinds of loops* the classic $o51oop, the $o5(ntil 1oop, the $o5%hile 1oop, and the 6or5-ext 1oop.
Do(oo)s
The most basic form of loop in #isual Basic is the $o51oop. +ts construct is !ery simple*
$o
('ode to execute)
1oop
This, "uite simply, executes the block of code, and when it reaches 1oop, returns to the beginning of
the $o 1oop and executes the same block of code again. The same block of code will be repeatedly
executed until it is told to stop executing. .o let7s try to apply this to our problem of generating the
6ibonacci series*
7im : $s Integer
7im + $s Integer

7o
7e%ug.-rint :

: " + ; :
+ " : < +
=oop

And, belie!e it or not, this code works8 %ell, sorta. +f you try to run this code, it will indeed generate
the 6ibonacci series9 howe!er, it will continually generate and print out the next number infinitely55or,
in this case, until it reaches an o!erflow error. This is known as the problem of the infinite do5loop, one
that all programmers will experience, and some "uite fre"uently.
'*it Do
.o we clearly need some way to escape from the $o51oop. )ou could, of course, simply nd the
program once you ha!e calculated enough !alues, but what if you still need to perform tasks after
you7re done calculating: The answer is to use the xit $o statement. %hene!er your program reaches
an xit $o statement within a loop, it will exit the current loop.
.o, let7s try a somewhat different approach to the 6ibonacci problem. %e decide that we want to
calculate only eight !alues of the 6ibonacci series, so we7ll keep a counter and increment it each time
throughout the loop. Then, once the counter reaches eight, we7ll exit the loop.
-u%lic 2u% 8ain>?
7im : $s Integer
7im + $s Integer
7im cnt $s Integer @)ur counter.
cnt " /
7o
7e%ug.-rint :
: " + ; :
+ " : < +

If cnt >" A Then
Exit 7o
Else
cnt " cnt ; /
End If
=oop
End 2u%
And now we7re talking8 This program successfully computes and prints out the first eight !alues of the
6ibonacci series.
Do #ntil
As an alternati!e approach to nesting an +f5.tatement inside the loop, and in!oking xit $o once we7re
done looping, #isual Basic pro!ides a $o (ntil statement. +ts syntax is the following*
$o (ntil (xpression)
('ode to execute)
1oop
(xpression) can be any legal logical expression that we wish to e!aluate to determine whether or not
to exit the loop. ach time the program reaches 1oop it will e!aluate this expression. +f the expression
is True, it will exit the loop for us, but otherwise it will continue looping.. .o let7s try rewriting our
6ibonacci program to use a $o5(ntil loop instead of xit $o.
-u%lic 2u% 8ain>?
7im : $s Integer
7im + $s Integer
7im cnt $s Integer @)ur counter.

cnt " /

7o Bntil cnt >" A
7e%ug.-rint :

: " + ; :
+ " : < +
cnt " cnt ; /
=oop
End 2u%
;ere we7!e replaced the hideous +f cnt <4 = Then ... lse* xit $o with a !ery simple (ntil cnt <4 =.
%e must, howe!er, still be sure to increment our counter e!ery time through the loop, or else the (ntil
expression will ne!er be True, resulting in an infinite $o 1oop.
Do +hile
+n the place of $o (ntil, you can also use $o %hile. +ts syntax is the following*
$o %hile (xpression)
('ode to execute)
1oop
(xpression) can be any legal logical expression that we wish to e!aluate to determine whether or not
to exit the loop. ach time the program reaches 1oop it will !erify that this expression is True, and if it
is 6alse, it will exit the loop for us. Thus, instead of exiting when an expression is True, it now exits
only once this expression is false. 1et7s try rewriting our 6ibonacci program to use a $o5%hile loop
instead of a $o5(ntil loop.
-u%lic 2u% 8ain>?
7im : $s Integer
7im + $s Integer
7im cnt $s Integer @)ur counter.
cnt " /
7o Chile cnt < A
7e%ug.-rint :
: " + ; :
+ " : < +
cnt " cnt ; /
=oop
End 2u%
,or(-e*t oo)s
+n situations where you merely want to run the loop a predefined number of times, it can become
"uite tiresome to ha!e to create and manage a counter for each loop, which is why we also ha!e
something called a 6or5-ext 1oop. This kind of loop allows you to specify a counter, to tell it to count
from one number to another each time through the loop, and to exit once the counter has reached its
upper limit. The syntax is as follow*
$im + As +nteger
6or + 4 (+nteger) To (+nteger)
('ode to execute)
-ext +
%e used the !ariable name >+> abo!e, as it is the most common name used for 6or51oops9 howe!er,
you can use any !ariable name you want, so long as the !ariable is of the type +nteger. -ow, let7s
impro!e our 6ibonacci program e!en further*
-u%lic 2u% 8ain>?
7im : $s Integer
7im + $s Integer
7im cnt $s Integer @)ur counter.
.or cnt " / To A
7e%ug.-rint :
: " + ; :
+ " : < +
=oop
End 2u%
+n the example abo!e, we first dimensioned cnt as an +nteger, and then, in the declaration of the 6or5
-ext loop, set its !alue to ?. ach time through the loop, the !alue of cnt was incremented by ? until it
reached =, at which point the loop was executed.
'*it ,or
As with $o 1oops, there is a statement that can be used to exit a 6or5-ext loop, and it is called xit
6or. .imply in!oke this statement anywhere within a 6or5-ext loop and the current loop will be exited.
Ste)
By default, the !ariable used in the declaration of the 6or5-ext loop is incremented by ? each time
through the loop9 howe!er, if you want to increment this !alue by a different amount each time
through the loop, you can simply append .tep (+nteger) to the end of the 6or5-ext loop declaration. +f,
for instance, we wanted to print out e!ery e!en number counting backward from @A to A, we could do
this using the following code*
7im I $s Integer

.or I " 0 To 2tep <0
7e%ug.-rint I
Dext I
.o there you ha!e it now you can use loops all o!er your #isaul Basic B programs. These are one of
the most useful tools you ha!e. )ou might want to bookmark this tutorial so that later you can
reference back to this great #BB loop examples.
Exit For and Exit Do Statement in isual !asic "
7 For###$ext loop condition can be terminated by an Exit For statement. :onsider the following statement
bloc$.
7im x $s Integer
.or x " / To /
-rint x
If x " , Then
-rint #The program exited at x",#
Exit .or
End If
Dext
The preceding code increments the "alue of x by + until it reaches the condition x ) =. The Exit For
statement is executed and it terminates the For###$ext loop. The Following statement bloc$ containing
Do###%hile loop is terminated using Exit Do statement.
7im x $s Integer
7o Chile x < /
-rint x
x " x ; /
If x " , Then
-rint #The program is exited at x",#
Exit 7o
End If
=oop
8ith...End 8ith statement
8hen properties are set for ob>ects or methods are called# a lot of coding is included that acts on the
same ob>ect. !t is easier to read the code by implementing the %ith###End %ith statement. /ultiple
properties can be set and multiple methods can be called by using the %ith###End %ith statement. The
code is executed more quic$ly and efficiently as the ob>ect is e"aluated only once. The concept can be
clearly understood with following example.
Cith Text/
..ont.2iEe " /5
..ont.Bold " True
..ore4olor " v%Fed
.Geight " 01
.Text " #Gello Corld#
End Cith
!n the abo"e coding# the ob>ect Text+# which is a text box is e"aluated only once instead of e"ery
associated property or method. This ma$es the coding simpler and efficient.

Potrebbero piacerti anche