You are on page 1of 17

CONTROL STRUCTURES

CHAPTER OBJECTIVES Create scripts that use arithmetic, comparison, and logical operators Create conditional expressions Use If Then, Select Case, and Switch Case decision control structures to alter the execution order of a script Use Do While, While Do, and For Next looping control structures to repeat bloc s of code Create nested bloc s of code Operators !oth "!Script and #a$aScript support assignment, concatenation, arithmetic, comparison, and unar% operators& 'ssignment operators are used to assign a $alue or an ob(ect to a $ariable& #a$aScript and "!Script use the e)ual sign, *+,, as their assignment operator& #a$aScript"!Script$ariable + $alue. $ariable + $alue

The concatenation operator is used to append expressions, such as a string and a $ariable& #a$aScript uses the plus, */,, while "!Script uses the ampersand *0,& 1xamplesdocument&write 2*The price of * / totNumber / *apples is * / tot3rice 4. document&write 2*The price of * 0 totNumber 0 *apples is * 0 tot3rice 4 Arithmetic operators allow %ou to perform mathematical calculations on $alues and $ariables&
VBScript / 5 6 8 JavaScript / 5 6 8 Description 'ddition Subtraction 7ultiplication Di$ision Example x/% x5% x6% x8%

Control Strucutres

Dr. M. Abdur Rob

Control Structures There are two t%pes of programming statements in "!Script and #a$aScript- action statements and control statements& Action statements 9 consist of code that carries out a tas , such as displa%ing text or assigning a $alue to a $ariable& These statements are usuall% executed in the order the% are written 2termed as linear programming4& Control statements 9 allow %ou to conditionall% determine both whether and how an action statement is executed, and the order in which action statements are executed& There are three t%pes of control statements that are supported b% both "!Script and #a$aScript and can be used in both client5side and ser$er5 side scripting& oopin! statements 9 allow %ou to conditionall% repeat a bloc of code&

Branchin! statements 9 allow the program to decide which of two or more bloc s of code to run, basing its decision on some identified criteria in the control statement& Jumpin! statements " allow %ou to conditionall% exit a code bloc and (ump to another section of code within %our program&

Control Strucutres

Dr. M. Abdur Rob

Decision control structures The I# Then statement is the most fre)uentl% used decision control structure& The If Then statement allows a script to alter the order in which statements are executed, on the basis of a conditional expression& The conditional expression tests whether a certain condition is true or false The Select Case statement pro$ides more than two options and is supported onl% in "!Script& #a$aScript uses a S$itch Case statement to pro$ide the same functionalit%&
The s%ntax for the If Then statement in "!Script isIf 2conditional expression4 then action statements else action statements end if The s%ntax for the If Then statement in #a$aScript isIf 2conditional expression4 then : action statements ; else : action statements ;

#a$aScript uses brac ets 2:4 to start and end the control structure, "!Script uses the <end if= to declare that the control structure has ended& Con%itional expressions often consist of two expressions and a comparison operator& The following table lists comparison operators used in conditional expressions in both #a$aScript and "!Script&
Con%ition Bein! teste% 1)ual to Not e)ual Cess than Dreater than Cess than or e)ual to Dreater than or e)ual to JavaScript Operator + + 2no space4 @+ A B A+ B+ JavaScript Example $ar> ++ $ar? $ar> @+ $ar? $ar> A $ar? $ar> B $ar? $ar> A+ $ar? $ar> B+ $ar? VBScript Operator + AB A B A+ B+ VBScript Example $ar> + $ar? $ar> AB $ar? $ar> A $ar? $ar> B $ar? $ar> A+ $ar? $ar> B+ $ar?

Control Strucutres

Dr. M. Abdur Rob

Example' emaillist&htm
AhtmlBAheadB AtitleBIf Then StatementsA8titleB A8headB Abod%B Ah> align+,center,BExpression TestA8h>B Aform method+EpostE name+Efrm>E action+E(a$ascript-$oid2F4EB Ainput t%pe +EtextE $alue+EGGE name+EtxtNameE siHe+EIEB (ameAbrBAbrB )hich color %o *ou pre#erG ApBAinput t%pe+EradioE chec ed name+EColorEBRe%A8pB ApBAinput t%pe +EradioE name+EColorEBBlueA8pB Ainput t%pe+EsubmitE $alue+EChooseE name+EbtnChooseE onClic +Ecolorpic 24E.BA8pB A8formB AscriptB function colorpic 24: $ar strName + window&document&frm>&txtName&$alue. if2document&frm>&ColorJFK&chec ed++true4: window&alert2strName / E is a red personE4. ; else: window&alert2strName / E is a blue personE4. ; ; A8scriptB A8bod%BA8htmlB

"iew-

emaillist#S&htm

emaillist"!&htm
Explanation In #a$aScript $oid is a special operator that does nothing& "oid will cause nothing to occur, which pre$ents an error to occur in code that is expecting an action to occur& The button triggers a script function called colorpick(). The colorpic 24 function will access the $ariables set up in the form& The conditional expression compares the first radio button, Color[0], with a true string& If it is true, the statements between the brac ets :; will be executed& This is the script statement that will be executed if the conditional statement e$aluates to true& If the statement does not e$aluate to true these statements will be executed& The else statement is optional&

S*ntax o# script Aform method+EpostE name+Efrm>E action+E(a$ascript-$oid2F4EB Ainput t%pe+EsubmitE $alue+EChooseE name+EbtnChooseE onClic +Ecolorpic 24E.BA8pB if2document&frm>&ColorJFK&chec ed++true4:

window&alert2strName / E is a red personE4. else: window&alert2strName / E is a blue personE4.

Control Strucutres

Dr. M. Abdur Rob

The example below illustrates how to process the same form using "!Script& Note onl% the colorpic 24 function is shown here&
Ascript language+,$bscript,B function colorpic 24 dim strName + window&document&frm>&txtName&$alue if2document&frm>&Color2F4&chec ed+true4 then window&alert2strName / E is a red personE4 else window&alert2strName / E is a blue personE4 end if end function A8scriptB

o!ical Operators ' lo!ical operator is used to compare two or more conditional expressions at the same time& The% are different for #a$aScript and "!Script&
Java Script 00 Example if22a++>4002b++?44 VB Script 'ND Example if22a+>4 and 2b+ ? 44 +eanin! If both expressions are true, the result is true& If either expression is false, the result is false& If either expression is true, or both are true, the result is true& If both are false, the result is false& Used to negate a single expression& If the expression is true, the result is false& If the expression is false, the result is true&

LL

if22a++>4LL2b++?44

MN

if22a+>4 or 2b+ ? 44

if 2@2a ++ >44

NMT

if2not2a + >44

It is clear that "!Scriot is simpler than the #a$aScript, and all pre$ious examples that is also true&

Control Strucutres

Dr. M. Abdur Rob

(este% I# Then Statements Oou can nest one If Then statement within another If Then statement& The process of nesting can be done indefinitel%& The following example shows a nested If Then example&

Example in VBScript' IF grade B IP TQ1N document&write 2*1xcellent@,4 1CS1 IF grade B RP TQ1N document&write 2*'bo$e '$erage@,4 1CS1 IF grade B SP TQ1N document&write 2*'$erage@,4 1ND IF 1ND IF 1ND IF

Example in VJavaScript' if 2grade B IP4 then : document&write 2*excellent@,4 ; else : if 2grade B RP4 then : document&write 2*abo$e a$erage@,4 ; else if 2grade B SP4 then : document&write 2*a$erage@,4 : ;

Control Strucutres

Dr. M. Abdur Rob

Select Case Statements The Select Case statement, an extension of the If Then statement, is used to include more than two conditions in the conditional expression& The statement could be bro en into man% nested If Then statements, but if %ou use a Select Case statement, %our code will be shorter, and also easier to follow& This statement is used mostly with server-side script since it is only supported by VBScript.
1xample- caseselect"!&htmAhtmlBAheadB AtitleBCase Select StatementA8titleB A8headB Abod% bgcolor+ET!>!SD1E text+ETFFFFIFEB Ah>BCase Select in "!ScriptA8h>B Ascript language+E$bscriptEB dim str3 str3 + > select case str3 case > window&alert 2EThe cost is UE 0 str34 case ? window&alert 2EThe cost is UE 0 str34 case else window&alert 2EThe cost is UE 0 str34 end select A8scriptB A8bod%B A8htmlB

Vie$ caseselectVB&htm The statement chec s to see if str3 is e)ual to >, and when that condition is true the statements related to that case are executed& If str3 was initialiHed to I, the case else would be executed& Example o# neste% I, THE( an% Select Case' Vie$ !i#t#in%erVB&htm co%e Vie$ !i#t#in%erVB&htm )e- pa!e

Control Strucutres

Dr. M. Abdur Rob

S$itch Case Statements #a$aScript contains a Switch Case statement that is similar to the "!Script Select Case statement& !oth allow %ou to e$aluate multiple statements& #a$aScript uses the e%word switch to identif% the beginning of the statement& The entire statement is enclosed within curl% braces 2:;4&
Ascript language+,(a$ascript,B function gi$eNumber24: $ar str3. str3 + document&frm&Number&$alue. switch 2str34: case >window&alert 2*Oou pic ed number >,4. brea . case ? window&alert2*Oou pic ed number ?,4. brea . case Vwindow&alert2*Oou pic ed number V,4. brea . defaultwindow&alert2*Oou pic ed a number that wasn=t >, ? or V,4. brea . ; ; A8scriptB

The switch could be replaced with the following If Then statementsIf2str3++>4: window&alert 2*Oou pic ed number >,4. ; else if 2str3++?4: window&alert 2*Oou pic ed number ?,4. : else if2str3++V4: window&alert 2*Oou pic ed number V,4. ; else: window&alert2*Oou pic ed a number that wasn=t >, ? or V,4. ;

Control Strucutres

Dr. M. Abdur Rob

oop Structures Using a loop structure, %ou can repeat action statements or control statements an% number of times& To list >FF elements in an arra% would ta e >FF statements without a loop structure and approximatel% R statements with a loop structure& The statements contained in the loop are called the bod% of the loop, and ma% consist of a single statement or se$eral statements& 1ach repetition of a loop is called iteration& The number of iterations is referred to as a loop in%ex varia-le& 'n up%ate statement is used to determine how to change the loop index $ariable& If %ou ne$er update the loop index $ariable the loop will continue to run without a natural ending, this is called an in#inite loop& The loop uses a conditional expression to determine when to stopWthe loop stops when the conditional expression is true& There are two main looping structures While Do loops 9 the Do While loop is an alternati$e The For Next loops 9 the For In loop is an alternati$e The )hile Do loop will repeat a bloc of code for as long as a conditional expression is e$aluated as true& The following is the s%ntax for a While Do loop in #a$aScript& while2conditional expression4 : action statements. update statement. ;

Control Strucutres

Dr. M. Abdur Rob

The following example uses the While Do loop s%ntax abo$e to displa% the elements of an arra%&
AhtmlBAheadB AtitleBWhile DoA8titleB A8headB Abod%B Ascript language+E(a$ascriptEB document&write2EAh>BDepartmentsA8h>BE4. $ar strCists + new 'rra%24. strCists JFK + ESportsE. strCists J>K + ETo%sE. strCists J?K + E7usicE. strCists JVK + E!oo sE. strCists JXK + EFoodE. $ar num7ax + strCists&length. $ar i + F. 88New arra% and filling the arra%

88using length propert% of the arra%

while2i @+ num7ax4: document&write22strCistsJiK4 / EAbrBE4. i//. ; document&write2EAbrBThere are E / i / E departmentsE4. A8scriptB A8bod%BA8htmlB
S*ntax o# Co%e $ar strCists + new 'rra%24. $ar num7ax + strCists&length. $ar i+ F. Explanation This initialiHes the arra%& This sets a $ariable to the length of the arra%, this $ariable will act as the final $alue for the update statement& The $ariable is i initialiHed to Hero and this will be incremented each time the loop is executed& The $ariable i will represent the loop index $ariable& This is the conditional expression that will be e$aluated e$er% iteration of the loop& This uses the index $ariable to print all the elements of the arra%& This increments the loop index $ariable& Some t%pe of increment has to be made or the loop will run fore$er& The // is a unar* operator&

while2i @+ num7ax4: document&write22strCistsJiK4 / *AbrBE4. i//.

Control Strucutres

10

Dr. M. Abdur Rob

.nar* Operators Unar% operators are used to alter a $alue of a $ariable& In #a$aScriptOperator // 55 5 Purpose Increments a counter b% > Decrements a counter b% > Negation- changes the sign to the in$erse sign Example Count + // Count Count + 55 Count 5Count Result i# Count / 0 Count + S Count + X Count + 5Y

Do )hile oops The Do While loop structure is similar to the While Do structure& The onl% difference is the conditional e$aluation is done at the end of the loop, which means there will be at least one iteration& !elow is the s%ntax for a Do While loop in #a$aScript&
do : action statements. update statement. ; while 2conditional expression4.

Example in VBScript' %o$hileVB&htm


AhtmlBAheadB AtitleBDo WhileA8titleB A8headB Abod%B Ascript language+E$bscriptEB dim aNumber aNumber + Y dim i i+F do while i A+ aNumber window&alert2i4 i+i/Y loop A8scriptB A8bod%BA8htmlB

Control Strucutres

11

Dr. M. Abdur Rob

,or (ext oops The For Next loop, li e the Do While loop, repeats action statements for a fixed number of times& Qowe$er the s%ntax is $er% different& The For Next loop identifies not onl% the conditional expression but also the loop index number and the update statement as parameters in the *for, statement& The following is the s%ntax for the "!Script For Next loop&
For CoopIndex + start1xpression to endNumber step stepNumber 'ction statements Next

The following is an example of utiliHing the "!Script For Next loop&


Ascript language +,$bscript,B dim startNum, endNum, stepNum, I startNum + F endNum + Y stepNum + ? for i + startNum to endNum step stepNum window&alert2i4 next A8scriptB

#a$aScript also supports the For Next loop, and its s%ntax is as floows& Notice that the semicolons separate each statement from the next&
for 2 start1xpression. conditional expression. stepNumber4 : action statements. ;

The following is an example of utiliHing the #a$aScript For Next loop&


Ascript language+,(a$ascript,B for 2$ar i +F. IA+Y. I+I/>4: document&write2*Oour number is * / I / *AbrB,4. ; A8scriptB

Control Strucutres

12

Dr. M. Abdur Rob

,or In oops The For In loop is similar to the For Next loop in that the% both allow %ou to repeat action statements& Qowe$er, the For In loop is most often used to retrie$e the properties of ob(ects& The For In loop retrie$es information about the properties of an ob(ect and the collections of the ob(ect& !elow is the s%ntax for implementing the For In Coop using #a$aScript&
for2$ariable in ob(ect4 : action statements. ;

The following is an example of For In loop in "!Script&


ForIn"!&htm AhtmlBAheadBAtitleBFor InA8titleBA8headB Abod% bgColor+ETFFFFPPE B Ah>B1lements of the 3roduct 'rra%A8h>B Ascript language + E"!scriptEB dim 3roducts2Y4 3roducts2F4 + E3encilsE 3roducts2>4 + E3ensE 3roducts2?4 + E3aperE 3roducts2V4 + E7ar ersE 3roducts2X4 + ENotepadsE 3roducts2Y4 + EScissorsE dim i i+F <New arra% and populating the arra%

<For Coop to print the arra% items for each each1lement in 3roducts document&write23roducts2i4 0 EAbrBE4 i + i/> next A8scriptB A8bod%BA8htmlB

Vie$ ,orInVB&htm

Control Strucutres

13

Dr. M. Abdur Rob

Sample Pro1ect' Pro1ect 023


Pro%uctOr%erVB&htm
AhtmlB AheadBAtitleB3roduct Mrder FormA8titleBA8headB Abod% bgcolor+ETFFCCPPEB Ah> align+EcenterEBAfont color+ETIFFFFFEBCalculate Oour MrderA8fontBA8h>B Aform method+EpostE name+frm3rod action+E(a$ascript-$oid2F4EB AcenterB Adi$ align+EleftEB Atable border+EFE width+EIVZE height+EVF>EB AtrB Atd width+ESXZE height+E?RVE align+ErightE rowspan+EREB Ah? align+EcenterEBAfont color+ETIFFFFFEB>FF !lac 3ens@A8fontBA8h?B Ah? align+EcenterEBAimg border+EFE src+Eblac pens&gifE width+E?YSE height+E>P?EBA8h?B A8tdB Atd width+ESFZE height+EVRE align+ErightEBAfont color+ETIFFFFFE face+ETrebuchet 7SEB3rice-A8fontBA8tdB Atd width+ERZE height+EVREBA8tdB Atd width+EXSZE height+EVREB Afont color+ETIFFFFFEB Ainput t%pe+EtextE name+EpriceE siHe+ESE $alue+E?I&FFEB A8fontB A8tdB A8trB AtrB Atd width+ESFZE height+EXVE align+ErightEBAfont color+ETIFFFFFE face+ETrebuchet 7SEB[uantit%-0nbsp.A8fontBA8tdB Atd width+ERZE height+EXVEBA8tdB Atd width+EXSZE height+EXVEB Afont color+ETIFFFFFEB Aselect name+E)uantit%E siHe+E>EB Aoption selected $alue+E>EB>A8optionB Aoption $alue+E?EB?A8optionB Aoption $alue+EVEBVA8optionB A8selectB A8fontB A8tdB A8trB AtrB Atd width+ESFZE height+EXVE align+ErightEBAfont color+ETIFFFFFE face+ETrebuchet 7SEBState-A8fontBA8tdB Atd width+ERZE height+EXVEBA8tdB Atd width+EXSZE height+EXVEB Afont color+ETIFFFFFEB Aselect name+EstateE siHe+E>EB Aoption $alue+EF&FIYE selectedBIllinoisA8optionB Aoption $alue+EF&FREBIndianaA8optionB Aoption $alue+EFEBMtherA8optionB

Control Strucutres

14

Dr. M. Abdur Rob

A8selectB A8fontB A8tdB A8trB AtrB Atd width+ESFZE height+EVYE align+ErightEBAfont color+ETIFFFFFE face+ETrebuchet 7SEBDeli$er% 7ethod-A8fontBA8tdB Atd width+ERZE height+EVYEBA8tdB Atd width+EXSZE height+EVYEB Afont color+ETIFFFFFEB Aselect name+EshippingE siHe+E>EB Aoption selected $alue+EF&F?EBStandard U3SA8optionB Aoption $alue+EF&FYEBM$ernightA8optionB Aoption $alue+EFEB3ic upA8optionB A8selectB A8fontB A8tdB A8trB AtrB Atd width+E>>>ZE colspan+EVE height+EXXEB Ap align+EcenterEBAfont color+ETIFFFFFE face+ETrebuchet 7SEBOour Total is-A8fontBA8tdB AtdBAinput t%pe+EtextE name+EtotalE siHe+E>>E $alue+EF&FFEBA8tdB A8trB AtrB Atd width+E>>>ZE colspan+EVE height+EXXEB Ap align+EcenterEB Afont color+ETIFFFFFEB A8fontB A8tdB A8trB AtrB Atd width+E>>>ZE colspan+EVE height+E?REB Ap align+EcenterEB Ainput name+EbtnSubmitE t%pe+EbuttonE $alue+ECalculate 7% Mrder Now@E onClic + Ecalc3rod24EB A8tdB A8trB A8tableB A8di$B A8centerB A8formB Ascript language+E$bscriptEB function calc3rod24 dim str3rice, str[uantit%, strState, strTotal str3rice+document&frm3rod&price&$alue str[uantit%+document&frm3rod&)uantit%&$alue strState+document&frm3rod&state&$alue strShipping+document&frm3rod&shipping&$alue strTotal+22str3rice6str[uantit%4/2str3rice6str[uantit%46strState / 2str3rice6str[uantit%46strShipping4 document&frm3rod&total&$alue+ strTotal end function A8scriptB A8bod%B A8htmlB

Vie$ Pro%uctOr%erVB&htm
Control Strucutres

15

Dr. M. Abdur Rob

4E5 TER+S
Action statements 9 consist of code that carries out a tas , such as displa%ing text or assigning a $alue to a $ariable& Arithmetic operators 5 allow %ou to perform mathematical calculations on $alues and $ariables& Boolean expression 2 a conditional expression. an expression that e$aluates to true or false& Branchin! statements 9 allow the program to decide which of two or more bloc s of code to run, basing its decision on some identified criteria in the control statement& Comparison operator " is used to compare two or more expressions& Con%itional expression 9 is an expression that is e$aluated b% the scripting engine as true or false& Control statements 9 allow %ou to conditionall% determine both whether and how an action statement is executed, and the order in which action statements are executed& Decision control structures 5 allow %ou to alter the execution order of action statements on the basis of conditional expressions& I# Then statement 2 the most fre)uentl% used decision control structure& In#inite loop " when a loop continues without a natural ending& Jumpin! statements " allow %ou to conditionall% exit a code bloc and (ump to another section of code within %our program& o!ical operator " is used to compare two or more conditional expressions& oop in%ex varia-le " a $ariable that eeps trac of the number of iterations& oop structures 5 allow %ou to repeat action statements on the basis of conditional expressions& oopin! statements 9 allow %ou to conditionall% repeat a bloc of code& .nar* operator " used to alter a $alue of a $ariable&

6uic7 6ui8'
>& What is the name of the expression statement that is e$aluated b% the scripting engine as true or falseG ?& Which statement is the most fre)uentl% used decision control structure& V& Which decision control statement pro$ides more than two options and is supported onl% in "!ScriptG X& Can an% select or switch statement be substituted for b% nested If Then statementsG Y& If %ou ne$er update the loop index $ariable, the loop will continue to run without a natural ending& What is this calledG S& What is the least amount of times a While Do loop executesG R& What is the least amount of times a Do While loop executesG I& Which loop is used to obtain properties of an ob(ectG

Control Strucutres

16

Dr. M. Abdur Rob

Control Strucutres

17

Dr. M. Abdur Rob

You might also like