You are on page 1of 32

Microsoft Technology Associate Series

Software Development
Fundamentals
EXAM 98361

Fo

rE

va
lu

at
io

On
ly

COURSEWARE 83611

at
io

va
lu

rE

Fo

On
ly

UnderstandingCoreProgramming
LessonObjectives
Bytheendofthislesson,youwillbeableto:
Explainhowcomputersstoreprogramsanddatainmemory.

Demonstratecomputerdecisionstructures,includingflowchartsandpseudocode.

Identifyandexplainthebestwaystohandlerepetition.

On
ly

ComputerStorageandDataTypes

ComputerMemory
PrimaryStorage(MainMemory)

at
io

Computersstoreprogramsandtheirinstructionsinvarioustypesofmemory.Thissectionofthelessonwillacquaintyou
withthosetypesofmemory,theirfunctionsandkeytermsthatdescribetheiruse.

Primarystorageistheonlytypeofmemorythatisdirectlyaccessiblebythecentralprocessingunit(CPU).TheCPU
continuouslyreadsinstructionsstoredthereandcarriesthoseinstructionsoutasrequired.Anydataactivelyoperatedon
isalsostoredthere.

va
lu

Historically,primarystorageincomputersusedtubes,ormagneticdrums.Bythemid1950s,thoseunpredictable
methodswerealmostentirelyreplacedbystillunwieldy,magneticcorememory.
Theinventionofthesolidstate(nomovingparts)transistorchangedeverything.Thetransistorledtounprecedented
miniaturizationandincreasedreliability.
Modernrandomaccessmemory(RAM)hastakenoverasthechieftypeofprimarystorage.RAMisphysicallysmall,light
andmuchlessexpensivethanitspredecessors.TherearemanysubtypesofRAM(DIMM,SIMM,DDRnowDDR2,and
DDR3),buttheybehaveinsimilarways.Theyarevolatile(theyneedelectricitytoretaindata).

rE

VirtualMemory

WhentheCPUneedstostoreinformationfromaprogram,itwillusetheavailablemainmemory.However,thereare
timeswhennotenoughmemoryisavailabletostorealltheinformationthattheCPUistryingtosave.Virtualmemoryis
harddrivediskspacesetasidetoactlikephysicalmainmemory.Althoughmuchslowerthanmainmemory,virtual
memorycanexpandmainmemorysothatprogramsthatotherwisecouldnotruncanrun.

Fo

ProcessorRegisters

Processorregistersarephysicallylocatedinsidetheprocessor.Eachregisterholdsaboutawordofdata.Wordhere
meansachunkofdata32bitsinsize,notawordliketheoneyoufindindictionaries;soadword(doubleword)wouldbe
64bits.Youmayencountera32bitboundaryinx86homecomputers.TheCPUinstructsthearithmeticandlogicunit
(ALU)toperformcalculationsorlogicaloperationsonthisdata(orwiththehelpofit).Registersprovidethefastest
responseofalldatastorage.

83611v1.00CCILearningSolutionsInc.

ProcessorCache(SRAM)
Cacheisslowerthanregisters,butisfasterthanotherformsofmemoryfurtherdownthehierarchy.Itisanextensionof
thememoryoftheregisters;however,itonlystoresanddoesnotcompute.

Figure11

On
ly

Multilevelcachesetupisoftenused:

Primarycacheisthesmallestandfastest,andlocatedinsidetheCPU.

Secondarycacheissomewhatlargerandslower,andislocatedjustofftheCPU.

TheCPUcommunicatestotheprimarystorage.IftheinformationrequestedbytheCPUisnotintheregistersorcache,
therequestissentthroughamemorybusviaamemorymanagementunit(MMU).

TheMMUdeterminesiftheinformationisintheRAMorneedstoberetrievedfromthemassstoragedevice.TheMMU
doesthiswiththeuseofitsTranslationLookasideBuffer(TLB),whichholdsatablematchingvirtualaddressesto
physicaladdresses.AlthoughtheMMUisusuallyintegratedintotheCPU,itcansometimesbeaseparatechip.

at
io

BIOS(BasicInput/OutputSystem)

Ifallmemorywerevolatile,computerswouldhavetobetaughthowtostartupeverytimetheywereturnedon.Unlike
RAM,registersandcache,BIOSisnonvolatile.BIOSisprimarystoragecontainingasmallstartupprogramusedto
bootstrapthecomputer.Bootstrap,whichcomesfromthephrasepullyourselfupbyyourbootstraps,meanstoreada
largerprogramfromnonvolatilesecondarystoragetoRAMandstarttoexecuteit.

va
lu

TheBIOSisoftenreferredtoasReadOnlyMemory(ROM).However,notonlycanitbeaccessedrandomly(likeRAM),
butitcanbealteredasinupdateyourBIOS,orflashyourBIOS(deletethecurrentinstructions).

SecondaryStorage

SecondarystorageisnotdirectlyaccessiblebytheCPU.Thecomputeraccessesitviainput/outputchannels.Likethe
BIOS,itisnonvolatile(doesnotlosethedatawhenthedeviceispowereddown)andismuchlessexpensivethan
primarystorage.
Harddiskdrives(HDDs)areusuallyusedassecondarystorage.
Accesstime(thelengthoftimeittakestoreaddata)variesbasedonthetypeofmemory:

HDDtypicallyrequiresafewthousandthsofasecond(milliseconds).

rE

RAMneedsbillionthsofasecond(nanoseconds).

Fo

Thephysicalstructureandlocationofeachtypeofthememorycausesthevariationintheaccesstime.Primarymemory
isveryclosetotheCPUandissolidstate(ithasnomovingparts),whereasHDDsarefartherawayandarecomprisedof
spinningmedia,whichincreasesaccesstime.

Someotherexamplesofsecondarystoragetechnologiesare:

ExternalHDDs

Flashmemory(e.g.,USBflashdrives/keys/thumbdrives)

Floppydisks(old,seldomused)

Magnetictape,(generallyusedonlyforbackup)

Papertape(obsolete)

Punchedcards(obsolete)

DVD/CD/BluRayRAMdisks

Theseotherdevicesareoftenformattedaccordingtoafilesystemformat(e.g.,FAT,FAT32,NTFSandCDFS).

83611v1.00CCILearningSolutionsInc.

TertiaryStorage(TertiaryMemory)
TertiarystorageisoftenhandledbyroboticretrievalofHDDsortapedrivesfromalargephysicalarrayofdisks.
1.

Thecomputerrequeststheinformation.

2.

Adatabasetellstherobotwherethedatais.

3.

Therobotphysicallymovestothelocationinthewarehouse.

4.

Itpicksthemedia(usuallytapebackup).

5.

Ittakesthemediatothereader/writer.

6.

Thereaderaccesses/writestheinformationrequested.

7.

Therobotreturnsthemediatoitspositioninthewarehouse.

MemoryStacks

On
ly

Themethodofretrievingdata,albeitslowly,isasfollows:

Thestackisaworkingareaofmemorythatgrowsandshrinksdynamicallywiththedemandsofyourexecutingprogram.

at
io

Memorystacksareregionsofmemorywheredataisaddedorremovedinalastinfirstoutmanner.Asafunction
executes,itcanadddatatothetopofthestackandbeaccessedquickly.Asthefunctionfinishes,itwilleliminatethat
datafromthestack.

Pop

va
lu

Push

Figure12

Thismethodofstorageisveryefficient;however,dataistransientandmustbecopiedtoothermemoryifitisneeded
afterthefunctionfinishes.

rE

Theactualdatastoredonthestackistheaddressofthefunctioncallthatallowsthereturnstatementtoreturntothe
correctlocation.Memoryundercontrolofthestackissaidtohavebeenallocatedonthestack.

Fo

Thestackssizedependsonthemicroprocessor.Itcanbeassmallasafewdozenkilobytes,orupto64KB,with8KB(or
2pages)reservedforoverflowerrorcontrol.YoucanoverridethestacklimitatcompiletimeAssigningmoredatatothe
stackthanisavailablecancauseastackoverfloworsystemaccessviolationerror.

Heaps

Applicationsneedtoallocatespecificamountsofmemorytostoretheirdata.Thatallocatedmemoryiscalledaheap.
Theapplicationcanmaketheheapanysize,butisusuallylessthan16KB.Aheap,therefore,allowsformemory
optimizationandisolation,andisindependentofmicroprocessorpagesizerestrictions.

Heapmemoryisthelevelabovevirtualmemory.
Whenaprocessiscreated,adefaultheapisalsocreatedfortheprocess.Anapplicationcanusetheprocessheapforits
memoryallocations,andtheheapgrowsandshrinksaccordingly.However,performancecansufferiftheamountand
typeofmemoryallocationsinthedefaultheapcausetheheaptobecomefragmented.
Notethatthetotalsizeofobjectsallocatedontheheapislimitedonlybyyoursystem'savailablevirtualmemory.

83611v1.00CCILearningSolutionsInc.

DataTypes
Overview
Whenyouaregoingtostoreapieceofdatainthecomputer,youneedtostoreitinaspecificcontainer.Thatcontainer
iscalledavariable.Thedifferentkindsofvariablesarecalleddatatypes.Differentdatatypesareneededtostore
differentkindsofdata.Eachprogramminglanguagecontrolsitsowndatatypes.Ingeneral,datatypesfallintothree
broadcategories:Numeric,TextandOther.
Mostprogramminglanguageshavesimilardatatypes,evenifthenamesdifferslightly.

On
ly

Historically,programmersusedcodesuchastheDimstatementtoreservespaceforthedatathatneededtobestored.
TheDimstatementshowsverysimplyhowthecomputerhandlesuserdata.
WhenVisualBasicprogrammerswritethecode:DimAasInteger,theyaretellingthecomputertoReserveaDimension
of4bytesofspaceinmemory,callitA,andallowittoholdawholenumberbetween2,147,483,648through
2,147,483,647(signed).
Whendeclaringavariable,youmustremembertwothings:

thetypeofdatayouwanttostoreinit,and

thesizeofdatayouwanttostoreinit.

AlthoughthetermDataTypeismostcommonlyused,DataTypeandSizeisactuallyabetterterm.

TypeofData

at
io

Avariablecanbecomparedtoaphysicalcontainer.Forexample,ifyouwanttostorewater,abucketisamuchbetter
containertypethanathreeringbinder,butifyouwerestoringyourautobiography,thebinderwouldbepreferred.We
storenumbersinnumericdatatypesandtextintextdatatypes

SizeofData

va
lu

Forefficiency,youshouldreserveaslittlespaceaspossibletoholdyourdata.Justasyouwouldnotrenta40foot
shippingcontainertoholdasinglephonebook,youwouldnotwanttostorethecontentsofafourbedroomhouseina
shoppingcart.Youneedtherightsizecontainerforthedatayouwanttostore.

DataTypestoStoreNumbers

Certainfactorsmustbeconsideredwhenusingnumericdatatypes:
Aredecimalsinvolved?Ontheotherhand,willthestorednumberalwaysbeawholenumber(integer)?
Isasigninvolved(suchasthetemperatureis3)?

Howbigisthenumber?

Whatlevelofaccuracyisneeded?

rE

Integers(wholenumbers)canbestoredinvariablesofthefollowingtypes:

Integer(orint32),forregularsizedwholenumbers(uptoabout2billion)

Long(orint64),forlargewholenumbers(9.2x1018)

Fo

Short(orInt16),forsmallwholenumbers(uptoabout33thousand)

Byte,forverysmallwholenumbers(0to256)

SByte,abytewithapositiveornegativesignedattached(from127to+127)

Decimalscanbestoredinvariablesofthefollowingtypes:

Decimal,fornumbersrequiringahighlevelofprecision(uptoabout28digits)

Single,forregularsizedfloatingpointnumbers(upto8decimalaccuracyandabout1x1040digitsinsize)

Double,forverylargefloatingpointnumbers(upto18decimalaccuracyandabout1x10310digitsinsize)

83611v1.00CCILearningSolutionsInc.


Thememorysizerequirementsforthesedatatypesareasfollows:
Nominalstorage
allocation
1byte
16bytes

Double(doubleprecision
floatingpoint)

8bytes

Integer/Int32
Long(longinteger)/
Int64/longlong
SByte
Short(shortinteger)/
Int16
Single(singleprecision
floatingpoint)

4bytes
8bytes

UInteger/UInt32
Ulong/UInt64

4bytes
8bytes

0through255(unsigned)
0through+/79,228,162,514,264,337,593,543,950,335

(+/7.9...E+28) withnodecimalpoint;0through+/
7.9228162514264337593543950335with28placesto
therightofthedecimal;
smallestnonzeronumberis+/
0.0000000000000000000000000001(+/1E28)
1.79769313486231570E+308through
4.94065645841246544E324fornegativevalues;
4.94065645841246544E324through
1.79769313486231570E+308forpositivevalues
2,147,483,648through2,147,483,647(signed)
9,223,372,036,854,775,808through
9,223,372,036,854,775,807(9.2...E+18)(signed)
128through127(signed)
32,768through32,767(signed)

at
io

4bytes

1byte
2bytes

3.4028235E+38through1.401298E45fornegative
values;
1.401298E45through3.4028235E+38forpositive
values
0through4,294,967,295(unsigned)
0through18,446,744,073,709,551,615(1.8...E+19)
(unsigned)
0through65,535(unsigned)

va
lu

UShort/UInt16

Valuerange

On
ly

CommonDatatype
Names
Byte
Decimal

2bytes

DataTypestoStoreText

rE

Mostprogramsalsodealwithtext,whetherdisplayinginformationorcapturingtextenteredbytheuser.Textisusually
storedintheStringdatatype,whichcancontainaseriesofletters,numbers,spacesandothercharacters.AStringcan
beofanylength,fromasentenceoraparagraphtoasinglecharactertonothingatall(anullstring).
Foravariablethatwillalwaysrepresentjustonecharacter,thereisalsoaChardatatype.Ifyouonlyneedtoholdone
characterinasinglevariable,youcanusetheChardatatypeinsteadofaString.
Acharactertype(oftencalledchar)maycontainasingleletter,digit,punctuationmarkorcontrolcharacter.

Fo

Somelanguageshavetwoormorecharactertypes:

ASCIIsinglebytetypeforcharacters.

Unicodemultibytetypeforcharacters.

Characterscanbecombinedintoastringofcharacters.Thestringcanincludenumbersandothernumericalsymbolsbut
thesewillbetreatedastext.Youcannotperformnumericcalculationsonstrings.Youcanaskthecomputertocalculate
thelengthofthestring;therebyitcanparticipateinacountcalculation,butyoucannottellthecomputertoaddtwo
strings.Youcan,however,combinetwostringsusingtheprocessofconcatenationwhichmeans"joiningtogether"(see
theexamplesbelow).Youcanstorenumbercharactersinastring(like6).Thisdatatypeisusedtostorenumberssuch
asaphonenumberwhennumericalcalculationswillneverbeperformedonthedata.

83611v1.00CCILearningSolutionsInc.


Goodprogrammingpracticeinvolvesusingcomments,orremarks,throughouttheprogramtoallowother
programmerstounderstandwhatishappeningandwhyyoucodedacertainway.Althoughmostprogramming
languagesallowremarks,theyusedifferentmethodsofputtingthemintocode.Thecodeinthisbookfollowsthe
VisualBasicmethod,whichiswithasinglequotationmark,a.Thecomputerdoesnotreadanythingontheline
afterthequote.InolderVisualBasiccode,youwillseetheremarkstartedwiththeREMstatement;whichiswhy
youwillhearprogrammerssay,forexample,JustREMoutthatcode,meaningConvertthecodetoremarksso
thecomputerwillnotrunit,butdonotdeleteitincaseyouneedtorunthecodelater.

Example1:
As Integer
As Integer
As Integer

On
ly

Dim A
Dim B
Dim C
A = 6
B = 3
C = A
Print

+ B
C this code would yield 9

at
io

Example2:
Dim A As String
Dim B As String
Dim C As String
A = 6 string variables require quotes
B = 3
C = A + B this code will cause an error, so I have REMed it out
C = A & B this code is valid, the ampersand (&) is the concatenation symbol
Print C this code would yield 63

va
lu

Inmostlanguages,astringisequivalenttoanarrayofcharacters;however,Javausesdistincttypes(java.lang.Stringand
char[ ]).
Literalsforcharactersandstringsareusuallysurroundedbyquotationmarks:sometimes,singlequotationmarks(')are
usedforcharacters,anddoublequotationmarks(")areusedforstrings.
ExamplesofcharacterliteralsinCsyntaxare:

'B'
'$'

ExamplesofstringliteralsinCsyntax
are:

Remarks in C are made

"B"

by using a forward

"MyDog"

slash/asterisk

'\t'(tabcharacter)

combination (/*) as in
/* blah blah blah */

Fo

'3'

rE

Eachcharacterwillrequireeither1or2bytestostorethedata,dependingontheprogramminglanguageusedandthesystem
beingused.Characterstringsandstringvariablesaresimplymultiplecharactersattachedtogether;therefore,thememorysize
requirementissimplythenumberofcharactersmultipliedbythesizeofeachcharacter(1or2bytes).

DataTypestoStoreOtherInformation
Inadditiontotextandnumbers,programssometimesneedtostoreothertypesofinformation,suchasatrueorfalse
value,adateordatathathasaspecialmeaningtotheprogram.

Boolean
Forvaluesthatcanberepresentedastrue/false,yes/no,oron/off,VisualBasichastheBooleandatatype.ABoolean
variablecanholdoneoftwopossiblevalues:TrueorFalse.

Date
Althoughyoucanrepresentdatesortimesasnumbers,theDatedatatypemakesiteasytocalculatedatesortimes,such
asthenumberofdaysuntilyourbirthdayorthenumberofminutesuntillunch.

83611v1.00CCILearningSolutionsInc.

Object
Insomecases,thetypeofdatayouneedtostoremaybedifferentatdifferenttimes.TheObjectdatatypeallowsyouto
declareavariableandthendefineitsdatatypelater.

Structures:YourOwnDataTypes
Astructureisageneralizationoftheuserdefinedtype(UDT)supportedbyearlierversionsofVisualBasic.

Composite

On
ly

Structuresareusefulwhenyouwantasinglevariabletoholdseveralrelatedpiecesofinformation.Forexample,you
mightwanttokeepanemployee'sname,telephoneextensionandsalarytogether.Youcoulduseseveralvariablesfor
thisinformation,oryoucoulddefineastructureanduseitforasingleemployeevariable.Theadvantageofthestructure
becomesapparentwhenyouhavemanyemployeesandthereforemanyinstancesofthevariable.
Youcancombinedataitemsofdifferenttypestocreateastructure.Astructureassociatesoneormoreelementswith
eachotherandwiththestructureitself.Whenyoudeclareastructure,itbecomesacompositedatatype,andyoucan
declarevariablesofthattype.

Thememorysizerequirementsforthesedatatypesareasfollows:

DateTime/Date
Object(class)

4byteson32bitplatform
8byteson64bitplatform
Dependsonimplementing
platform

va
lu

UserDefined(structure)/
(inheritsfromValueType)

Nominalstorage
allocation
Dependsonimplementing
platform(often1byte)
8bytes

Valuerange

TrueorFalse

at
io

CommonDatatype
Names
Boolean

Whenyouneedtostoremorethanonetypeofdatainasinglevariable,youcanuseacompositedatatype.Composite
datatypesincludearrays,structuresandclasses.

0:00:00(midnight)onJanuary1,0001through11:59:59
PMonDecember31,9999
AnytypecanbestoredinavariableoftypeObject
Eachmemberofthestructurehasarangedetermined
byitsdatatypeandindependentoftherangesofthe
othermembers

UnderstandComputerDecisionStructures

rE

Overview

Computerprogramscanruninalinearfashion.Thatis,theycanfollowstepbystepproceduresandreachthesame
conclusioneverytime.However,doingsowouldleadtoverysimplisticapplications.Programsbecomepowerfulwhen
weallowthemtomakedecisionsbasedonacertaindynamicsetofcircumstances.

Fo

BeforewegetintoanyDecisionStructure(inwhichthecomputerdeterminesthecorrectpathtotake),wewillfirst
examinesomesimplegraphicmethodstorepresentwhatisgoingoninsidevariouscomputerprograms.Thosemethods
areflowchartsandpseudocode.

Flowcharts

Aflowchartisavisualrepresentationofastepbystepsolutiontoaproblem.
Flowchartsareusedinanalyzing,designing,documentingormanagingaprocessorprogram.Theyarenotrestrictedto
computerprogramming;anyprocesscanbeflowcharted.
Aflowchartisacommonwaytorepresentanalgorithm(i.e.,process).Eachstepintheprocessisrepresentedbyabox.
Thefunctionofthestepdeterminestheshapeofthebox.Arrowslinkingtheboxesshowtheorderandpotentialpaths.A
flowcharttrulyshowstheflowoftheprocessandthereforetheflowoftheprogramming.
Theflowchartcanbeconsideredthemostimportantpartoftheprogrambecausealltheimportantdecisionsaremade
there.Itmightbeeasiertogetsignofffromanontechnicalmanager.
Flowchartsareprogramminglanguageindependent,sotheycanbecreatedfirst,evenbeforealanguageisselected.

83611v1.00CCILearningSolutionsInc.

at
io

On
ly

Thefollowingexampledemonstratesthesimplesttypeofflowchart,alinearprogression(fortheexamplewewillchart
washingadog):

Figure13

va
lu

Symbols

SummingJunction,Or,Collate,Sort

PredefinedProcess,InternalStorage,Document,MultiDocument

Extract,Merge,StoredData,Delay

rE

Process,AltProcess,Decision,Data(Input/Output)

Fo

Terminator,Preparation,ManualInput,ManualOperation

Connector,OffPageConnector,Card,PunchedTape

SequentialStorage,MagneticDisk,DirectAccessStorage,Display

All processes should flow from top to bottom or left to right. All arrow lines must be straight (curved lines are not
allowedinflowcharting).

Typicalflowchartsymbolsinclude:

Terminator
o Ovals,usuallycontainingthewordstartorend.
o Maycontainanotherphrasesignalingthestartorendofaprocess,suchas"submitenquiry"or"receive
product.

Arrows
o Directionoftravelwhenthecurrentprocessiscompleted.
o Directionofflow.

83611v1.00CCILearningSolutionsInc.


Processingsteps
o Rectangles.
o Somethingforthecomputertoperform,usuallyacalculation.

Data(Input/Output)
o Parallelogram.
o Example:GetXfromtheuser(Input);displayX(Output).

Decision
o Representedasadiamond(rhombus).
o Boolean(Yes/NoorTrue/Falsetest).
o Twoandonlytwoarrowsleavethissymbol:
AlwaysmarkthesearrowsTrueandFalse(orthelike).

Anumberofothersymbolsthathavelessuniversalcurrency,suchas:
o ADocumentrepresentedasarectanglewithawavybase.
o AManualinputrepresentedbyparallelogram,withthetopirregularlyslopingupfromlefttoright.Anexample
wouldbetosignifydataentryfromaform.
o AManualoperationrepresentedbyatrapezoidwiththelongestparallelsideatthetop,torepresentan
operationoradjustmenttoprocessthatcanonlybemademanually.
o ADataFilerepresentedbyacylinder.
o Connectors
Circles.
Convergingpathsorconnecttoanotherpage(usuallynotenoughroomonthecurrentpagetodisplay).

PseudoCode

at
io

On
ly

Pseudocodeisawayofexpressinginformationfromaflowchartinatext.Itisanintermediatestepbeforecoding.
Althoughitisgenerallynotprogramminglanguagespecific,itcanbewrittenwithabiastowardacertainlanguage.

va
lu

For the dog wash example, the pseudocode


couldbewritten:
1. Getthedog.
2. Getsoap.
3 Getwater.
4. Mixdog,waterandsoap.
5. Drythedog.

rE

Fo

Figure14

Syntax
Syntaxisawayofshowingthestructureofapieceofcodewithoutshowingaspecificexample.Itletsyouseehowthe
codeworksandtheargumentsneededtousethecode/structuresuccessfully.
ThesyntaxforthesumfunctioninExcelis:

SUM(number1,number2,...)

wherenumber1,number2,...are1to30argumentsforwhichyouwantthetotalvalueorsum.Itistheneasytousethe
codeyourself;forexample:

=sum(A2,C6)

83611v1.00CCILearningSolutionsInc.

IfDecisionStructures
TheIFdecisionstructureiscommontomanyprogramminglanguages.Itisthebasicbuildingblockofanydecision
structure.AdditionalfunctionalitycanbeaddedtotheIFstatementtomakeitmorepowerful;theseadditionscomein
theformoftheIfThenElseandIfThenElseIfstructures.

IfThen

Figure15

va
lu

at
io

On
ly

Thesameflowchartfromearlier,withanaddeddecisionstructure,wouldlooklikethis:

Althoughthesyntaxvaries,theifthenstructureiscommontomanyprogramminglanguages,includingVB,VBA,VB.Net,
C++,C#,Javaandmore.

Syntax:

rE

If(ConditionA)Then

(statementblockB)

EndIf

Fo

statementblockBisonlyperformedifconditionA
evaluatestotrue;ifitisfalse,gostraighttotheEnd
If.

10

83611v1.00CCILearningSolutionsInc.

IfThenElse

Figure16

If(conditionC)Then

(statementblockD)

statementblockDisonlyperformedifconditionC
evaluatestotrue.Whencompleted,gotoEndIf.

(statementblockE)

statementblockDisonlyperformedifconditionC
evaluatestotrue.Whencompleted,gotoEndIf.

Else

Fo

rE

EndIf

va
lu

at
io

On
ly

Usedwhenyouwanttoperformablockofcodeiftheconditionistrue,andyouwanttoperformadifferentblockof
codeiftheconditionisfalse.

83611v1.00CCILearningSolutionsInc.

11

IfThenElseIf
Foranextrachoice,youcanselectfromamongthreeanswers,youcanusetheIfThenElseIfstatement:

va
lu

at
io

On
ly

rE

Figure17

If number<0 Then
Print "Your number is negative"
Elseif number>0 Then
Print "Your number is positive"
Else
Print "Your number is zero"
End If

Fo

MultipleDecisionStructuresSuchAsSwitch/SelectCase

12

SometimesaBooleanexpression(true/false)istoolimiting.EventheIfThenElseIfstatementmightnotprovideenough
choice.Perhapsyouneedtodecideamongseveral(orevenmany)answers.YoucouldperformnestedIfstatements,
buttheyrequirealotofcodeandareconfusingtoreadandtroubleshoot.

83611v1.00CCILearningSolutionsInc.

Figure18

rE

va
lu

at
io

On
ly

Asaflowchart,anestedIfwouldlooklikethis:

AnestedIfThenElsestructureinpseudocode,fortheprecedingflowchart:

In most programming,

Fo

If Flight Points < 0 then


indents of code do not
Message There is an error with your points
affect the running of the
Else if Flight Points < 100 then
program. Indentation is
Message You are Bronze Status
used to help people read,
Else if Flight Points < 10,000 then
edit and troubleshoot
Message You are Silver Status
the code.
Else if Flight Points < 25,000 then

Message You are Gold Status

Else if Flight Points < 50,000 then


Message You are Platinum Status
Else
Message You are double Platinum Status
End If
End If
End If
End If
End If

83611v1.00CCILearningSolutionsInc.

13

at
io

On
ly

Instead,aSelectCase(VisualBasic)structurelookslikethis:

Figure19

SomerulesabouttheSelectCasestatementareasfollows:

Thecodeexecutesfromthetoptothebottom.

IfyoumatchtheCase,runthecodethere,andthengodirectlytotheEndCaseStatement.
TheCaseElsestatementwillrunifnoCaseismatched.

Thereisonlyonepossibleanswerfromthisstatement.

va
lu

Fo

rE

InPseudoCode(closetoVisualBasic):
Select Case Flight Points
Case < 0
There is an error with your Points
Case < 100
You are Bronze Status
Case < 1,000
You are Silver Status
Case < 10,000
You are Gold Status
Case < 25,000
You are Gold Status
Case < 50,000
You are Platinum Status
Case Else
You are Double Platinum Status
End Case

InPascal,C,C++,C#,andJava,thissamestructuralelement(althoughwithaslightlydifferentsyntax)iscalledaSwitch.

14

83611v1.00CCILearningSolutionsInc.

DecisionTables
Decisiontablesareapreciseandcompactwaytomodelcomplicatedlogic.
Likeifthenelseandswitchcasestatements,decisiontablesassociateconditionswithactionstoperformandallowfor
logictesting.However,decisiontablesaremorecompact,andareeasiertoeditbutnotaseasytotranslateintocode.
Decisiontablesareusedtoshowallthepossiblepathsinasimplematrix.

Structure
TableName
Conditions

ConditionAnswers(T/F)

Actions

PerformAction(Y/N)

Example(TroubleshootaLocalPrinter)

Answers

DoyouseetheprinterinyourPrinters
folderonyourcomputer?

Check/replacetoner.

Check/removepaperjam.

PerformActions

va
lu

Checkforprinterpowercablepluggedinto
wallandprinter.
CheckforprinterUSBcablepluggedinto
computerandprinter.
Install/reinstalltheprintdriver.

rE

Actions

at
io

Areanylightslitontheprinter?

Isthereawarninglightontheprinter?
Conditions

On
ly

Thesyntaxisasfollows:

Check/addpaper.

Fo

TheanswerstotheconditionsthatoccureventuallyleadtothedecisionfoundintheActionsarea.Forinstance,using
thefirstAnswercolumn,thereisnowarninglightontheprinterandthereisnoPrintersfolderbuttherearelightsonthe
printer. With these conditions met, we are led to the decision to install or reinstall the print driver to fix the printer
problem.
Thisisanoversimplifiedexample,withtheintenttoillustratetheconceptofdecisiontables.

EvaluatingExpressions
EvaluationVsComparison
InlanguagessuchasVisualBasic,thereisaninherentambiguitytotheequal=operator.Thesymbolcanmean
EvaluatetherightsideoftheequationandassignthevaluetotheleftsidesuchasA=1+3.Thismeaningissometimes
referredtoastheAssignmentOperator.Ontheotherhand,the=symbolcanmean,Comparetherightsidetotheleft
sideoftheequationandseeifitistrueaswith4=1+3,whichwouldbetrue.
ThisambiguityissolvedinlanguageslikeC#whichuses=onlyforevaluation,withthe==operatorforcomparison.

83611v1.00CCILearningSolutionsInc.

15

MathematicalFormulas(Evaluation)
Computersevaluatemathematicalformulasintheproperorder(alsoknownasorderofoperationsorprecedence).
Automaticallyevaluateexpressionsusingthefollowingorder:

Operator

1st(highest)
2nd
2nd
3rd
3rd
4th
4th

brackets
exponents
roots(e.g.cuberoot)
division
multiplication
addition
subtraction

Inwritten
mathematical
expression
(4+2)
42
3
4
42
4X2
4+2
42

Incommon
computer
syntax
(4+2)
4^2
4^(1/3)
4/2
4*2
4+2
42

Hierarchy

On
ly

Example:4+2*3
Ifyou(incorrectly)evaluatedfromlefttoright
4+2=6then*3=18
However,youmust(andthecomputerwillautomatically)usethecorrectorderofoperations,therefore:
MultiplicationbeforeAddition
2*3=6,then+4=10,whichisthecorrectevaluation

at
io

B.E.D.M.A.S.

Brackets(),thenExponents2(includingroots),thenDivision/andMultiplication*,thenAddition
+andSubtraction

ComparisonOperators
Operator
=(equal)

va
lu

ThefollowingtablesummarizesthecomparisonoperatorsinVisualBasic:

Examples

ReturnsTrueifthenumberontheleftsideisequalto
thenumberontherightside.

5=4(false)
4=5(false)
4=4(true)
5<>4(true)
4<>5(true)
4<>4(false)
5>4(true)
4>5(false)
4>4(false)
5<4(false)
4<5(true)
4<4(false)
5>=4(true)
4>=5(false)
4>=4(true)
5<=4(false)
4<=5(true)
4<=4(true)

ReturnsTrueifthenumberontheleftisnotequalto
thenumberontheright.

rE

<>(notequalto)

Description

ReturnsTrueifthenumberontheleftisgreaterthan
thenumberontheright.

<(lessthan)

ReturnsTrueifthenumberontheleftislessthanthe
numberontheright.

>=(greaterthan
orequalto)

ReturnsTrueifthenumberontheleftisgreaterthan
orequaltothenumberontheright.

<=(lessthanor
equalto)

ReturnsTrueifthenumberontheleftislessthanor
equaltothenumberontheright.

Fo

>(greaterthan)

16

83611v1.00CCILearningSolutionsInc.

Inthisexercise,youwillcreatechartsaswellasworkwithcodeinExcel.
1.

Createaflowchartforgettingjuicefromtherefrigerator.

2.

Createaflowchartforgoingtothestoreinacar.

3.

Createadecisionstructureforobediencetrainingadog.

4.

Createaflowcharttocompareexpressions.

A = CDbl(Range("B4").Value)
B = CDbl(Range("B5").Value)
MsgBox A & " > " & B & " Is " & (A > B)
MsgBox A & " < " & B & " Is " & (A < B)
MsgBox A & " = " & B & " Is " & (A = B)

ThefirsttwolinesdeclarethevariablesAandB,whichwillholdthenumericvaluesusedinthisprogram;they
usetheCDblstatementtoconvertthetextfromExcelcellB4andExcelcellB5intonumericvalues.Finally,the
lastthreelinescreateexpressionstocomparethetwovariablesusingthreebasiccomparisonoperators,and
displaytheresultsofthoseexpressionsinthreemessageboxes.

On
ly

ThefollowingcodeisenteredforyouinExcelusingVisualBasicforApplications
Dim A As Double
Dim B As Double

OpenExcel2007.

FromtheOfficeButton,clickExcelOptions.

at
io

5.
6.
7.

ClicktheTrustCentertabtotheleftandthenclickTrustCenterSettings.

8.

FromtheMacroSettingsmenu,clickEnableallmacros(notrecommended;potentiallydangerouscodecan
runandTrustaccesstotheVBAprojectobjectmodel.ClickOK.

9.

InthePopularcategory,clickShowDevelopertabintheRibbonandclickOK.

va
lu

10. OpentheLesson1Samples.xlsmfilefromyourstudentdatafiles.

Fo

rE

11. FromthefirsttabcalledIF,typeanumberineachoftheyellowcells(C6,H6andM6)andclickeachbutton,
noticingtheresultofeach:

ThefirstmessageboxwilldisplayTrueifA(thenumberyouenteredinthefirsttextbox)isgreaterthanB(the
number you entered in the second text box); otherwise it will display False. The second message box will
displayTrueifAislessthanB,andthethirdmessageboxwilldisplayTrueifbothnumbersarethesame.

12. Trytypingdifferentnumbersintothetextboxestoseehowtheresultschange.
13. KeepLesson1Samples.xlsmopen.

83611v1.00CCILearningSolutionsInc.

17

IdentifytheAppropriateMethodforHandling
Repetition
Overview

On
ly

Leftunregulated,aprogramproceedsthroughitsstatementsfrombeginningtoend.Simpleprogramscanbewritten
withonlythisunidirectionalflow(asyousawintheDecisionStructuressection).However,muchofthepowerandutility
ofanyprogramminglanguagecomesfromitsabilitytochangeexecutionorderwithcontrolstatementsandloops.
Controlstructuresallowyoutoregulatetheflowofyourprogram'sexecution.Usingcontrolstructures,youcanwrite
VisualBasiccodethatmakesdecisionsorrepeatsactions.Othercontrolstructuresletyouguaranteedisposalofa
resourceorrunaseriesofstatementsonthesameobjectreference.

Loops

Loopsareprogrammingstructuresusedtorepeattherunningofcodeuntilacertaincondition(orsetofconditions)is
met.

For
While

DoWhile
DoUntil
RepeatUntil

ForLoops

va
lu

at
io

Therearedifferentkindsofloops,whosesyntaxdoesvarywiththeprogramminglanguagebeingused.Here,wewill
focusonVisualBasicbecauseittendstobethemostverbose,whichcanhelpnewprogrammers:

Aforloopgetsitsnamefromthecodethatisoftenused.Itenablesyoutorepeatcodeaspecifiednumberoftimesand
isavailableinmostprogramminglanguages.
Hereisaforloopinapartialflowchart:

Fo

rE

InBasic(thisexamplewillrunthe
Statements10times;nomatterwhat
thevaluesofanyvariableoruserinput,
thestatementswillrun10times):
Dim I As Integer
For I = 1 To 10
[Statements]
Next I

Figure110

18

83611v1.00CCILearningSolutionsInc.

1.

FromtheLesson1Samples.xlsmfile,selectthetabcalledLoops.

2.

ChangethenumberincellC6andclickClicktoruntheFORloop.

3.

Repeatasnecessary.

4.

Keepthefileopen.

On
ly

at
io

WhileLoops

Mostprogramminglanguagesalsohaveconstructionsforrepeatingaloopuntilsomecondition(s)is/aremet.
Theterminologymaybeconfusing;thisstructureiscalledaWhileLoop(eventhoughthecodeusesDoWhile).

FromtheLesson1Samples.xlsmfile,selectthetabcalledLoops.

Fo

rE

1.

va
lu

BecausethecodewithinaWhileLoopmightneverberun(iftheexpressionisfalsetobeginwith),itisknownasapre
test,wheretheconditionisevaluatedbeforethestatementsarerun.
Do While (Condition)
[Statements]
Loop

2.

ChangethenumberincellG6andclickClicktoruntheDOWHILEloop.

3.

Repeatasnecessary.

4.

Keepthefileopen.

83611v1.00CCILearningSolutionsInc.

19

Do...WhileLoops
UnliketheWhileLoop(whosestatementsmightneverruniftheconditionisfalsetobeginwith),thestatementsinside
theDoWhileLoopmustberunatleastonce.Knownasaposttest,wherethestatementsarerunoncebeforethe
conditionisevaluated,thisstructureisoftenusedwhenyouneedtogetuserinputforeachiteration.
Syntax:

Do

ThesameconceptisusedforDoUntilLoop.
Do
[statements]
Until (condition is true)

at
io

Exampleinpseudocode
Do
Get item number from User
Calculate how much the product costs
Total = Total + new cost
Until (user enters done)
Print You owe & Total

On
ly

[statements]
While (condition is true)

Somelanguagesmayuseadifferentsyntaxforthistypeofloop;forexample,Pascalusesa
repeatuntilloop.

FromtheLesson1Samples.xlsmfile,selectthetabcalledLoops.

Fo

rE

va
lu

1.

20

2.

ChangethenumberincellL6andclickClicktoruntheDOloop.

3.

Repeatasnecessary.

4.

Keepthefileopen.

83611v1.00CCILearningSolutionsInc.

Recursion(CollectionControlledLoops)VersusIterative
Thetwomethodsofperformingloopsareiterationandrecursion.Insimpleterms,iterationmeansperformingateston
anitemtoseeifcertainconditionsaremet,andiftheyarenot,movingtothenextitemdisregardingtheoneyoujust
examined.Recursion,ontheotherhand,keepstrackofthepreviouselement(s).Infact,itusesthepreviousvalues(s)to
createthenewvalue.Theadvantagetoiterationisthatitrarelycausesanoverflowerrorbecauseitonlytracksonething
atatime.Thedisadvantagetoiterationisthatitdoesnotrememberthepreviousvalues,soevaluationmustbeginall
overeverytime.Conversely,recursionkeepstrackofallofthevaluesithasdealtwith,whichcancauseoverflowerrors.
However,recursioncanalsosolvemorecomplexproblemsthatrequireinformationfromthepreviousdatatobeusedby
thecurrentdata.

On
ly

Ineachrecursion,thereneedstobeabasecase,whichisthestartingpoint.

TwocommonexamplesoftenusedtoshowrecursionarefactorialsandtheFibonacciSequence.

Factorials

Insimplemathematicalterms,afactorialisapositivenumbermultipliedbyallthenumbersbetweenitselfandthedigit
one.
Forexample,6factorial=6!=6*5*4*3*2*1=720(zeroisnotusedinthefactorialseries).

at
io

Thefollowingparagraphisafunction,definedinwords,thatcalculatesafactorial.

Ifthenumberislessthanzero,rejectit.

Ifitisnotaninteger,rejectit.

Ifthenumberiszero,itsfactorialisone.

Ifthenumberislargerthanzero,multiplyitbythefactorialofthenextsmallernumber

Tocalculatethefactorialofapositivewholenumber(thatisnotzero)callitn.Youcancalculatethefactorialofn1,
thenmultiplyitbyn.Thisleadstoaninternalloopwhereinordertocalculatethenumber,thefunctionmustcallitself
forthenextsmallernumberbeforeitcanexecuteonthecurrentnumber.Thisisanexampleofrecursion.Inmath,this
appearsas:6!=6*5!

va
lu

Recursionanditeration(looping)arecloselyrelatedafunctioncanreturnthesameresultswitheitherrecursionor
iteration.Certaincomputationswilllendthemselvesbettertoonetechniqueortheother;youchoosethemostnatural
orlogicalapproach.
Youmustbecarefulbecauseevenwiththeusefulnessofrecursion,youcaneasilycreatearecursivefunctionthatnever
returnsaresultandcannotreachanendpoint.Sucharecursion(anditerationloopingaswell)causesthecomputerto
executeaninfiniteloop.Forinstance,ifyouweretoallownegativenumbers,youwouldget6!=6*5!=then4!3!2!1!
0!1!2!andyouwouldneverreachtheend.Itwouldcalculateforinfinity.

rE

Computerresourcesareanotherconcernwhenyoudealwithrecursion.Becauseyouarecallingthesamefunctionfrom
withinthefunctionitself,thecomputerhastotrackallthenumbersasyougo.Iteffectivelyhastorememberallphases
oftherecursionatonce.Thisrestrictioncancausestackoverflowsorsystemmemoryoverflows.

Fo

Therefore,youmustbeverycarefulincreatingrecursivefunctions.Itisagoodideatofollowanycodebyhandtomake
certainyoucalltherecursivefunctionexcessively(orinfinitely).Onemethodyoucanemployistosetupacounterto
countthenumberoftimesthefunctionscallsitself,soyoucanlimitthecallstoacertainpredefinedcount,thenyoucan
stopitfromrunningifitpassesthethreshold.Thereisnoabsolutemaximumnumberofinternalfunctioncalls;it
dependsonthefunctionitself.

Example:RecursiveFactorialFunction(n!=n*(n1)!)
Function factorial(ByVal n As Integer) As Integer
If n =< 1 Then
factorial = 1:
Exit Function
End If
factorial = n * factorial(n-1)
End Function

83611v1.00CCILearningSolutionsInc.

21

On
ly

Example:IterationFactorialFunctionn!=(n1)*(n2)*(n3)(1)
Function factorial (ByVal n As Integer) As Integer
factorial = 1
Dim a as Integer
For a = 1 To n
factorial = factorial * a
Next 'a
End Function
FromtheLesson1Samples.xlsmfile,selectthetabcalledFactorial.

2.

ChangethenumberincellB2andclickFactorialbyRecursion.

3.

Repeatasnecessary.

4.

ChangethenumberincellB2andclickFactorialbyIteration.

5.

Repeatasnecessary.

6.

Keepthefileopen.

va
lu

rE

at
io

1.

Fibonaccinumbers:

Inmathematics,theFibonaccinumbersarethenumbersinthefollowingsequence:

Fo

F0 F1 F2 F3 F4 F5 F6 F7 F8 F9 F10 F11 F12 F13 F14 F15 F16 F17

F18

F19

F20

0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765

ThefirsttwoFibonaccinumbersare0and1(althoughsomepeopleskipthe0,sothefirsttwonumbersare1and1).
Eachsubsequentnumberisthesumoftheprevioustwo.
Inmathematicalterms,thesequenceFnofFibonaccinumbersisdefinedbytherecurrencerelation

F n = F n -1 + F n -2 ,
Withseed(base)values

F 0 = 0 and F 1 = 1.

22

83611v1.00CCILearningSolutionsInc.

On
ly

TheFibonaccisequenceisnamedafterLeonardoofPisa,whowasknownasFibonacci(acontractionoffiliusBonaccio,
"sonofBonaccio").Fibonacci's1202bookLiberAbaciintroducedthesequencetoWesternEuropeanmathematics.The
sequencewasreportedearlierinIndianmathematics.Thissequenceproducescomplexandinterestingvisualeffects,as
showninthefigurebelow.

Figure111

at
io

1
1+1=2
2+1=3
3+2=5
5+3=8
8+5=13
13+8=21
21+13=34andsoon.

AFibonaccispiraliscreatedbydrawingarcsconnectingtheoppositecornersofsquaresintheFibonaccitiling;thisone
usessquaresofsizes1,1,2,3,5,8,13,21,and34;

Figure112

TheprecedingFibonacciareadiagramshowsawaytoseegraphicallytheeffectofthesequence.

va
lu

FromtheLesson1Samples.xlsmfile,selectthetabcalledFibonacci.

Fo

rE

1.

2.

ChangethenumberincellB2andclickcalculateFibonacciSeries.

3.

ClickClearSeries.

4.

Repeatasnecessary.

5.

ChangethenumberincellB2andclickFactorialbyIteration.

6.

Repeatasnecessary.

7.

Keepthefileopen.

83611v1.00CCILearningSolutionsInc.

23

UnderstandError(Exception)Handling
Inaperfectworld,noprogramwouldevercontainanyerrorsincode,andeverypossibleinputfromauserwouldbe
resolvedandnotcrashtheprogram.However,inpracticalterms,youneedtoknownotonlywhaterrorscanoccur,but
alsohowtohandlethemsotheydonotcrashyourprograms.Bydefinition,anexceptioncanbethoughtofasaspecial
conditionthatchangesthenormalflowofprogramexecution.Thewordspecialisambiguous,butcanbethoughtofas
somethingthatdoesnothelptheprogramrun.Frequentlyusedtermsarethrowinganexceptionoranexception
throw.

On
ly

TypesofErrors
Basically,errorscanbebrokendownintothreetypes:

Syntaxerrors

Runtimeerrors

Logicerrors

SyntaxErrors

Theseerrorsoccurwhenamistakeoccursinthespellingorpunctuationofcode.Theyareoftendiscoveredbythe
softwarealmostimmediately(oftenassoonastheprogrammerleavesthelineheorshewasworkingon).
A = Dogs

at
io

Example:
o

Here,thecomputerwilldetectanerroralmostassoonasitistyped.

ThereisamissingclosingquotationmarkafterDogs.

RuntimeErrors

va
lu

Syntaxerrorsarethemostcommontypeoferrors.Youcanfixthemeasilyinthecodingenvironmentassoonasthey
occur.

Runtimeerrorsareusuallyonlyfoundwhenthecodeisexecutedduringitsrunning(hencethenameruntime).
Runtimeerrorscanbereduced,butnoteliminatedcompletelyiftheprogramiscompiled(thecomputercandoa
thoroughcheckanddryrunofyourprogramtoseeifanyruntimeerrorswilloccur).

rE

Forexample,youmightcorrectlywritealineofcodetoopenafile.However,ifthefileiscorruptedoralreadyopenby
anotherprocess,theapplicationcannotcarryouttheOpenfunction,anditstopsrunning.Youcanfixmostruntime
errorsbyrewritingthefaultycode,thenrecompilingandrerunningit.

LogicErrors

Fo

Logicerrorsarethosethatappearaftertheapplicationisinuse.Theyshouldbecaughtatdesigntimeifthecoderis
careful,butthereareusuallysomanylinesofcodethattoexpectperfectionisunrealistic.Logicerrorsaregenerallythe
hardesttypetofix,becauseitisoftendifficulttofindwheretheyoriginate.
Example:
A = CountOfDogs
B = CountOfCats
Print The count of Cats is & A
o

Here,therewillbenonotificationfromthecomputerthatthereisanerror;itthinkseverythingisfine.

However,thecountofcatsisstoredinB,notA.

ExceptionHandling
VisualBasicsupportsbothstructuredandunstructuredexception(error)handling.Byinsertingexceptionhandlingcode
inyourapplication,youcanhandlemostoftheerrorsusersmayencounterandenabletheapplicationtocontinue
runningproperly.Youcanusestructuredandunstructurederrorhandlingtoplanforpossibleerrors,therebypreventing
themfromcrashingyourapplicationorproducinginaccurateresults.

24

83611v1.00CCILearningSolutionsInc.


Youshouldinsertexceptionhandlingcodeinanymethodthatusesoperatorsthatmaygenerateanexception,orthat
callsintooraccessesotherproceduresthatmaygenerateanexception.Often,programmerswillcodefunctionstocall
otherfunctions.Ifyoudonotcodeforerrorhandling,youwilloftennotknowinwhichfunctiontheerroroccurred.

StructuredExceptionHandling
Instructuredexceptionhandling,blocksofcodeareseparatedfromoneanother,witheachblockhavingatleastone
associatedhandler.Eachhandlerisspecifictothetypeofexceptionithandles.Whenanexceptionisthrown(occurs),
thecorrespondinghandlerscodeisexecuted.Asinglemethodcanhavemultiplestructuredexceptionhandlingblocks,
andtheblockscanbenestedwithineachother.

On
ly

UnstructuredExceptionHandling

TheOnErrorstatementisusedforunstructuredexceptionhandling.OnErrorisplacedatthebeginningofablockof
code.Ithandlesanyerrorsoccurringwithinthatblock.IfyouusemorethanoneOnErrorstatement,themostrecent
statementtakesprecedence.

ChoosingWhentoUseStructuredandUnstructuredExceptionHandling

Structuredexceptionhandlingistheuseofacontrolstructurecontainingexceptionsandfilterstocreateamechanismto
handleexceptions.Thisfeatureallowsyourcodetodistinguishbetweendifferenttypesoferrorsandreactappropriately.
Inunstructuredexceptionhandling,anOnErrorstatementhandlesallexceptions.

at
io

Structured exception handling is significantly more robust and flexible than unstructured exception handling. When
possible, use structured exception handling; however, you might use unstructured exception handling under the
followingcircumstances:
YouareupgradinganapplicationwritteninanearlierversionofVisualBasic(wherestructurederrorhandlingdid
notexist).

Youaredevelopingabetaversionofanapplicationandyouarenotconcernediftheprogramfailstoshutdown
gracefully.

You know in advance exactly what will cause the exception (so the On Error can be coded specifically for that
exception).

Adeadlineispressing,andyouarewillingtosacrificeflexibilityforspeed.

va
lu

Codeisshortenoughthatyouonlyneedtotestthebranchofcodegeneratingtheexception.

You need to use the Resume Next statement, which is not supported in structured exception handling. This
statementsimplystates,ifyoureachanerror,gotothenextlinewithoutcrashing.

Theuserwillinputnumbersratherthanletters.
Thenumberwillhaveacertainformat(xxxxxxxxxx).

Theuserwillnotinputanullstring.

Theuserhasasingletelephonenumber.

Fo

rE

Apart from what you choose to handle exceptions within your code, always take an objective look at your (and the
codes)assumptions.Forexample,whenyourapplicationaskstheusertoinputatelephonenumber,youmustbeaware
ofthefollowingassumptions:

Userinputmightbreachanyoftheseassumptions.Robustcoderequiresadequateexceptionhandling,whichallows
yourapplicationtorecoverfromsuchabreach.
You should use informative exception handling. Beyond stating an error has occurred, messages resulting from
exceptionhandlingshouldindicateexactlywhyandwherethingswentwrong.

TheTry...Catch...FinallyBlock

InnewerversionsofVisualBasic(notExcel),theTry...Catch...Finallyisanexampleofstructuredexceptionhandling.You
canTryasegmentofcode;ifanexceptionisthrown,itjumpsto,andrunsthecodeintheCatchblock.Afterthatcode
hasfinished,anycodeintheFinallyblockisrun.TheTrystatementrepresentsthebeginningoftheblock,whiletheEnd
Trystatementrepresentstheendoftheblock.

83611v1.00CCILearningSolutionsInc.

25


ExampleSyntax
Try
' Code here attempts to do something.
Catch
' If an error occurs, code here will run.
Finally
' Code in this block will always run.
End Try

LessonSummary
Youarenowableto:

On
ly

First,thecodeintheTryblockisexecuted.Ifitrunswithoutanexception,theprogramskipstheCatchblockandruns
thecodeintheFinallyblock.IfthecodeintheTryblockdoesthrowanexception,thecodeintheCatchblockisrun
immediately;thenthecodeintheFinallyblockisrun.

Explainhowcomputersstoreprogramsanddatainmemory.

Demonstratecomputerdecisionstructures,includingflowchartsandpseudocode.

Identifyandexplainthebestwaystohandlerepetition.

at
io

ReviewQuestions
WhatdoesRAMstandfor?
a. ReadAllMemory
b. RandomAccessMemory
c. ReadyAllMemory
d. RefreshAccesstoMemory

2.

Volatilemeans:
a. Electricitymustbeflowingforretention
b. Somememorycanstealdatafromothermemory
c. Memorycanlosedataeasily
d. Thememoryvaporsmustnotbebreathed

3.

UnlikeRAM,BIOSis:
a. Inexpensive
b. Notavailableatstartup
c. Notonthemotherboard
d. Nonvolatile

Fo

rE

va
lu

1.

MMM
Go online for
Additional
Review and Case
Scenarios

4.

Amemorystack:
a. Isanexampleoffirstin,firstoutstorage
b. Holdsmemoryaddresses
c. Hasitssizeiscontrolledbytheapplication
d. IsstoredintheBIOS

5.

AStringdatatypecanholdanumber:
a. True
b. False

26

83611v1.00CCILearningSolutionsInc.


6.

Identifythenameofeachflowchartsymbol:
Offpageconnector
Data
Process

On
ly

Decision
Display
Document
PredefinedProcess

Connector

at
io

Terminator

Syntaxis:
a. Thestructuretoformatcode
b. Awaytounderstandprogrammingusingrealworldexamples
c. Agenericrepresentationofapieceofcodeorfunction
d. Notusedinmodernprogramming

8.

Whatiscorrectaboutloops?
a. Thereisonlyonecorrectwaytocodethem
b. Theyareefficientatreusingcode
c. Theywillrunthesamewayregardlessofuserinput
d. Youdonotneedtotestthembecausetheyareeasytowrite

9.

Listthethreetypesoferrors:
a. ____________________
b. ____________________
c. ____________________

rE

va
lu

7.

Fo

10. WhichisanexampleofStructuredErrorHandling?
a. IF
b. Loop
c. OnError
d. Try...Catch...Finally

83611v1.00CCILearningSolutionsInc.

27

Fo

rE

va
lu

at
io

On
ly

28

83611v1.00CCILearningSolutionsInc.

at
io

va
lu

rE

Fo

On
ly

IT Starts Here.

Microsoft Technology Associate


Preparing Tomorrows Technology Workforce
Technology plays a role in virtually every business around the world. Possessing the fundamental
knowledge of how technology works and understanding its impact on todays academic and workplace
environment is increasingly importantparticularly for students interested in exploring professions involving
technology. Thats why Microsoft and Certiport are pleased to offer you the Microsoft Technology Associate (MTA)
certificationMicrosofts new entry-level credential that validates fundamental technology knowledge
among students seeking to build a career in technology.

rE

va
lu

at
io

On
ly

The Microsoft Technology Associate (MTA) certification is the ideal and preferred path to Microsofts
world-renowned advanced technology certification programs, such as Microsoft Certified Technology
Specialist (MCTS) and Microsoft Certified IT Professional (MCITP). MTA is sure to become the premier
credential for individuals seeking to explore and pursue a career in technology, or augment related pursuits
such as business or any other field where technology is pervasive.

Why Get Certified?

Fo

MTA validates students understanding of the key IT building blocks essential for intermediate study, while
more advanced certifications such as Microsoft Certified Technology Specialist (MCTS) and Microsoft
Certified IT Professional (MCITP) validate skills and experience with Microsoft products and IT solutions
developed using Microsoft technologies. Microsoft Certifications recognize and reward your abilities and
expertise as your career develops.
Whether you are new to technology, changing jobs, or a seasoned IT professional, becoming certified
demonstrates to customers, peers, and employers that you are committed to advancing your skills and
taking on greater challenges. In addition, certification provides you with access to exclusive Microsoft
Certified IT Professional (MCITP) resources and benefits, including opportunities to connect with a vast, global
network of MCPs.

www.ccilearning.com

You might also like