Hashan Punchihewa · o Memory Data Register (MDR) - A register that stores the data being either...

Preview:

Citation preview

ComputerScienceRevisionGuideDraft

HashanPunchihewa

1.1Hardware1.1.1 StructureandfunctionoftheprocessorRegisters

o Register-AregisterisasmallareaofmemoryinsidetheCPUtostoredata,withveryhigh-speedaccess.

o ProgramCounter(PC)–Aregisterwhichstorestheaddressofthenextinstruction.It

is incrementedafterbeing read. It controls thesequence inwhich instructionsareexecuted.Itisalteredasaresultofa“jump”instruction.

o Accumulator(ACC)-AregisterthatstorestheresultsofcalculationsbytheCPU.

o MemoryAddressRegister(MAR)-Aregisterthatstorestheaddressofthememory

locationcurrentlybeingeitherreadfromorwrittento.

o MemoryDataRegister(MDR)-Aregisterthatstoresthedatabeingeitherreadfrommemoryorwrittentomemory.ItactsasabufferbetweenmemoryandtheCPU.

o Current Instruction Register (CIR) - A register that stores the instruction to be

executed.Itsplitsinstructionsintotwoparts:theopcodeandoperand.Italsoholdstheopcodewhileitisbeingdecoded.IftheoperandisanaddressitissenttotheMAR,ifitisavalueitissendtotheMDR.ItmayalsosendanaddresstothePCfora“jump”instruction.

Components

o ControlUnit-Thecontrolunitcontrolsthefetch-decode-executecycleandmanagesthe execution of instructions, by transmitting control signals to other parts of thecomputersystem.Italsosynchronisesactionsusingitsin-builtclock.

o ALU - The ALU carries out arithmetic operations such as addition, and logical

operationssuchasgreaterthancomparisons.Italsoactsasaconduitthroughwhichallinput/outputtothecomputergoes.

Fetch-Decode-ExecuteCycle

1. Thecontentsoftheprogramcounterarecopiedintothememoryaddressregister.2. ThecurrentinstructioniscopiedfromRAMintothememorydataregister.3. Thecurrentinstructioniscopiedfromthememorydataregisterintothecurrent

instructionregister.4. Theprogramcounterisincremented,suchthatitpointstothenextinstruction.5. Theinstructionisdecoded.6. Theinstructionisexecuted.

FactorsaffectingtheperformanceoftheCPUo Clockspeed-Thehighertheclockspeed,themorefetch-decode-executecyclesthe

CPUcanperformpersecond.Themoreinstructionscanbeexecutedpersecond.Thelesstimeprogramstaketorun.

o Number of cores - The more cores, the more instructions the CPU can execute

concurrently.Therefore,moreprocessesthatcanberunsimultaneously.

o Cache-Themorecachememory,morefrequentlyaccesseddataandinstructionscanbestoredintheCPU.ThismeansRAMneedstobeaccessedlessoften.SignificantasaccessingcacheisquickerthanaccessingRAM.

ExamTechniqueIfasked“Describehowafastclockspeedimprovesaprocessor’sperformance”,mentionnotonlythatafasterclockspeedmeansmoreclockcyclespersecond,butfollowthroughyourargument,andmentionthatthismeanstherearemoreinstructionsexecutedpersecond,andtherefore,aprogramtakeslesstimetorun.CPUsvGPUsCPU GPUMIMD SIMDFlexible OptimisedHigherclock-rate Lowerclock-rateLesscores MorecoresComplexinstructions SimpleinstructionsBuses

o Bus – A medium through which data is transferred between components in acomputersystem.

o AddressBus-Unidirectionalbususedtotransfertheaddressofmemorytoberead

fromorwrittento,fromtheprocessortomemoryorinput/outputdevices.

o DataBus-Bidirectionalbususedtotransferdatabetweentheprocessorandmemoryorinput/outputdevices.

o ControlBus-Unidirectionalbususedtotransmitcontrolsignalse.g.‘read’,‘write’,

etc.fromtheprocessortomemoryorinput/outputdevices.Pipelining

o Pipelining-WherethestagesofaCPU’sfetch-decode-executecyclearecarriedoutatthesametimeonsequentialinstructions.Thismeansthataninstructionisfetched,atthesametimeasthepreviousone isbeingdecoded,andtheonebeforethat isbeingexecuted.

AdvantagesofPipelining DisadvantagesofPipeliningAlthough instructions take the same time,thedelaybetweencompletedinstructionsisreduced, increasing the throughput of theprocessor,increasingtheclockrate.

Pipeliningonlyworkswell,whenapieceofcode doesn’t contain many jumpinstructions.This isas theprocessormightloadtheincorrectbranch,inwhichcase,thepipelinehastoclearedandrestarted.

ExamTechniqueIfasked“ExplainhowpipeliningwouldhelpaCPUexecutethecodemorequickly”,thenrefertowhatpipeliningdoes,giveanexampleandcruciallymentionwhetherthecodehasnojumpinstructions.Architectures

o Von Neumann Architecture - This is where there is a single control unit, oneinstructionisprocessedatatimeinalinearsequenceinafetch-decode-executecycleandprogramsarestoredwithdata.Allowsself-modifyingcode.

o Harvard Architecture - Instructions and data are stored separately in their own

memories,andeachisaccessedwithaseparatebus,meaningtheCPUcanfetchbothinstructionsanddatasimultaneously.Thememoryforinstructionsmayberead-only.Thesizeofmemoryaddressesandinstructionaddressesmaybedifferent.

o ContemporaryArchitecture-InstructionsanddataarestoredseparatelyintheCPU

cache and there are separate pathways to the different types of data, thuswhenaccessing data from cache, the CPU will behave as if it followed pure Harvardarchitecture.Butinstructionsanddataarestoredtogetherinmainmemory,andthereisasingledatabusbetweentheCPUandmainmemory

1.1.2TypesofprocessorsCo-processors

o Co-processor–Anadditionalprocessorusedtosupplementthefunctionsandoffloadworkfromthemainprocessor.Itusuallyoptimisedforaspecificpurposee.g.maths-intensivecalculations.

o GPU – A co-processor optimised formaths-intensive calculations and highly data-

parallelcomputation.AnexampleofSIMD.Usesincludeprocessingpolygonvectorsforvideogames,bitcoinminingandmachinelearning.

RISCandCISC

o ReducedInstructionSetComputing(RISC)-Asimpleprocessordesign,containinganinstructionsetwithalimitednumberofinstructions,whereasingleinstructionperformsasingletask,andmorecomplextasksmostbeperformedbycombiningsimpleinstructions.

o ComplexInstructionSetComputing(CISC)–Acomplicatedprocessordesign,

containinganinstructionsetwithmanyinstructions,howeverasingleinstructionmaytakemultipleclockcycles.

FeaturesofRISC FeaturesofCISCSimplerhardware MorecomplexhardwareLessheat MoreheatFurtherawayfromhigher-levellanguages Closertohigher-levellanguagesLonger code taking more space in mainmemory

Shorter code taking less space in mainmemory

Compilerhastodomorework CompilerhastodolessworkEveryinstructiontakesoneclockcycle Instructionsmaytakemorethanoneclock

cycleLimitednumberofaddressingmodes ManyaddressingmodesEasiertocarryoutpipelining MoredifficulttocarryoutpipeliningParallelSystems Singleinstruction MultipleinstructionsScalarprocessors SISD(Singleinstruction,

singledata)MISD(Singleinstruction,multipledata)

Arrayprocessors SIMD(Singleinstruction,multipledata)

MIMD(Multipleinstruction,multipledata)

Multi-coreprocessors–Processorsconsistingofmultipleprocessingunits,thatcaneachrundifferentinstructionssimultaneously.(MIMD).Arrayprocessor(orvectorprocessor)–Aprocessorthatcanperformthesameinstructiononmultiplepiecesofdatasimultaneously.(SIMD).1.1.3InputandOutput

o InputDevice-Hardwareusedbyausertoputdataintoacomputersystem.

o OutputDevice-Hardwareusedtoreportinformationfromacomputersystemtoauser.

o RandomAccessMemory (RAM) -Volatile formof computermemory to store the

runningoperatingsystem,applicationsandopenfiles.Thismeansitiserasedwhenthecomputerisswitchedoff.Canbemodified.

o ReadOnlyMemory (ROM) - Non-volatile read-only formof computermemory tostorethecomputer’sbootsequence.Dataisretainedwhenthecomputerisswitchedoff.Cannotbemodified.

BarcodeReadersBarcode–Awayofstoringdatausingpatternsofdarklinesofdifferentwidths,pairsofwhichstoredigits.Barcodestypicallyhavestartorstopcodessotheycanbereadbothwaysandacheckdigit forerrorchecking.Typically,abarcodereaderusesa laserora lightsourcetoobtainareflectionofthelines.AdvantagesofaBarcodeReader DisadvantageofaBarcodeReaderFastdataentry BarcodescanbedamagedAccurate Can be difficult to get the barcode reader

intotherequiredpositionforlargeritems.ScannersOpticalCharacterRecognition(OCR)–Adevicethattransfershandwrittenorprintedtexttoeditable text on a computer by optically scanning the text to determine the shape ofcharacters.Ausewouldbeconvertinghandwrittendocumentsintoawordprocessorfile.OpticalMarkRecognition(OMR)–Adevicethatrecognisesthepresenceofamarkonasheetof paper by the reflection of light, the position of themarks conveys information to themachine.Ausewouldbescanninginamultiple-choicetest.MagneticInkCharacterRecognition(MICR)–Adeviceabletoreadinformationwritteninaspecial magnetic ink, which is also human-readable. A use would be reading in accountnumbersoncheques.PrintersAdvantagesofaDotMatrixPrinter DisadvantagesofaDotMatrixPrinterPossible toobtainmultiplecopiesbyusingcarbonpaper

Slowandpoorquality

NotpossibletoprintincolourAdvantagesofanInkjetPrinter DisadvantagesofanInkjetPrinterFasterandbetterqualitythanDotMatrix NeedstochangecolourcartridgesoftenPossibletoprintincolour LesscopiesaminutethanalaserprinterAdvantagesofaLaserPrinter DisadvantagesofaLaserPrinterFasterthananInkjetPrinter ExpensiveInk lasts longer so don’t need to changecartridgesasoften

Bulkyandheavy

MagneticStripeCardsMagneticStripeCard–Acardthatstoresdatabyusingthemagnetismofastripofmagneticmaterialonthecard.Thesearereadusingmagneticstripereaders.ActuatorsActuator–Amechanicaldeviceormotor,usedanoutputdeviceforthosewhoarevisuallyimpaired.

SensorsThesemeasuremovement:

o Gyroscope–Sensorthatmeasureschangesinorientation.o Accelerometer–Sensorthatmeasuresacceleration.o Altimeter–Sensorthatmeasuresaltitude.

StorageOpticalStorage–Astoragemediumwheredataisstoredinaformthatcanbeaccessedthroughlight.OpticalDiscs(e.g.CDs/DVDs/Blu-Rays)–Asecondarystoragemediumconsistingofadisc,withdataencodedontoit.Alasercanbeusedtoreaddatafromitandwritedatatoit.Bitsarerepresentedthroughhowandwhetherlightisreflected.MagneticStorage–Astoragemediumwherebitspatternswouldberepresentedbydifferentpatternsofmagnetism.HardDiskDrive(HDD)–Asecondarystoragemedium,madeofadiskconsistingofoneormoreplatters.Bitsarerepresentedbymagnetisedspotsontheplattersthatrotateathighspeeds. Platters are divided into tracks and tracks into sectors. A disk headwhichmovesradially (in/out towards thecentreof theplatter) isused towrite thedata to thecorrectsector,asthesectorspassesbelowit.MagneticTape–Aserialaccessmagneticsecondarystoragemedium,consistingofplasticfilm,thatstoresdatathroughmagnetism.FlashStorage–Anon-volatilecomputerstoragemediumthatreliesonnomovingparts,andinsteadstoresdatatoNANDflashgates.VirtualStorageVirtualStorage–Virtualstorageiswheremultiplephysicalstoragedrivesarepooledtogetherso they appear as a single logical storage drive. Examples include storage area networks,wheremanyphysicaldrivesareaccessedasasinglelogicaldriveacrossanetwork,andcloudstorage,where cloud storageproviders sell storage spaceonwhatappears tobea singlelogicalpool,butwhichspansmanyphysicaldrives.AdvantagesofCloudStorage DisadvantagesofCloudStorageEasilyexpanded Youneedaninternetconnection.Easilytransferred Easilyaccessed

1.2Software

1.2.1SystemsSoftware

o OperatingSystem–Systemsoftwarethatmanagesthehardwareofacomputersystem.

Functionsofanoperatingsystem

o Memorymanagemento Processorschedulingo Interrupthandling

Whyisschedulingneeded?

o Processasmanyjobsaspossibleintheleastamountoftime.o Ensurejobsareprocessedfairly.o Maximisethenumberofinteractiveusers.o Efficientuseofprocessortime.

SchedulingFirstComeFirstServed–Aschedulingpolicywherejobsareexecutedintheordertheyenterthereadyqueue.ShortestJobFirst–AschedulingpolicywherejobsaresortedinthereadyqueueinascendingorderofthetimerequiredandnewjobsareaddedinawaytopreservethisorderRoundRobin–AschedulingpolicywhereeachjobisgivenasetamountofCPUtime,andafterthatsetamount,thejobisinterruptedandsenttothebackofthereadyqueue;thenextjobinthequeuethenruns.Roundrobincannotactasaschedulingpolicyonitsown,itmustworkincombinationwithanother policy to choosewhich policy to go first. For example, first come first served incombinationwithroundrobin.Togethertheymakeaschedulingscheme.ShortestRemainingTime-Aschedulingpolicywherethejobwiththesmallestexpectedtimeuntilcompletionisselectedtorun;ifanewjobisaddedtothereadyqueuewithasmallerexpectedtimethanthecurrentlyrunningjobthenitwilltakeover.Multi-LevelFeedbackQueue–Aschedulingpolicywheretheprocessorcategorisesjobsintodifferentqueues,withdifferentpriorities.Jobsinaqueueofhigherpriorityarealwayschosentobeexecutedoverjobsinaqueueoflowerpriority,andtheschedulertakesjobsfromthefrontofthequeue.Jobsareusuallyinsertedathighestpriorityqueue.Jobsthattakeuptheentiretimeslicearedemotedtothenext lowestqueue. Jobsalwaysenterat thetailofaqueue.Thelowestqueueusesroundrobin.Insomeimplementations,whenajobblocksforI/O,thejobcanbepromotedtofavourI/Oboundjobs.Whyismemorymanagementneeded?

• Organisetheuseofmainmemorybyconvertinglogicaladdressestophysicaladdresses

• Allowprogramstosharememory• Protectprogramsfromusingthesamememory• Allowprogramslargerthanmainmemorytorun.

MemoryManagement

o Paging–Amemorymanagementschemeusedwithvirtualmemorywherememoryispartitionedintophysicalpagesanddataaredividedintologicalpages.Logicalpagesare stored on disk, and logical pages are assigned physical pages and loaded intomemoryastheyareneeded.Apagetablerecordswhichphysicalpageholdswhichlogical page. Pages are of the same size. Pages are not allocated contiguously inmemory.

o Segmentation–Awayofpartitioningwheredataisdividedintosegmentswhichare

ofdifferentsizes.Segmentsarestoredondisk,andloadedintomemoryastheyareneeded. Segments can represent complete programs, that can be executedseparately.

Programmerschoosethesegments,butnotpages.

o VirtualMemory–Whereanareaofthesecondarystorageisusedtosupplementmainmemory,whenmainmemorybecomesfull.Pagesorsegmentsareswappedbetweenmainmemoryandsecondarystorage.Thishappenssothatpartsoftheprogramnotcurrentlyinusemayberun,allowinglargeprogramstorun.

o DiskThrashing–Asituationwhichoccurswhenusingvirtualmemory,wherethereis

averyhighrateofdiskaccesses,suchthatmoretimeisspentswappingpagesthanprocessingtasks.

BIOS

o BIOS–Softwarethatrunsimmediatelyafteracomputerstartsuptocheckthatthesystemhardwareworks,byrunningapower-onself-test(POST),andloadsabootloaderoranoperatingsystemintomainmemory.

Interrupts

o Interrupt–Aninterruptisasignalsenttotheprocessorfromadevice/processneedsindicatingitneedsattention.Examplesofinterruptsincludeapowerfailureinterrupt,a system clock interrupt and an I/O interrupt. Different interrupts have differentprioritiesbasedontheirimportance.

o Whyaretheyused?

o Toobtainprocessortimeforahigherprioritytask.o Toindicateadevice/processneedsattention.

o Howacomputerhandlesaninterrupt:1. Completethecurrentfetch-decode-executecycle2. Checkthepriorityoftheinterrupt3. Ifitisofalowerprioritythanthecurrenttask,thenstop.4. PushthecontentsoftheCPU’sregistersontothestack

5. Loadtherelevantinterruptserviceroutinebysettingtheprogramcountertothefirstinstructionoftheinterruptserviceroutine

6. Aftertheinterruptserviceroutineisfinished,restorethevaluesoftheregisters,bypoppingthemfromthestack

7. Theoriginalprocesscontinues.

o InterruptServiceRoutine(ISR)–Aprocedureinanoperatingsystemordevicedriverwhichistriggeredtohandleaninterrupt.

o DeviceDriver–Systemsoftwarethatoperatesorcommunicateswithahardware

deviceattachedtoacomputer.Italsoprovidesasoftwareinterfacetothehardwaredeviceandinterruptserviceroutinesforhandlinganyinterruptsfromthehardware.

TypesofOperatingSystems

o RealTimeOperatingSystem–Anoperatingsystemthatgivesaresponsewithinaguaranteedtimeframe.

o Distributed Operating System – An operating system that runs allows multiple

computers,connectedthroughanetwork,toworktogetheronthesameproblem.

o Embedded Operating System – An operating system which is designed for anembeddedcomputersystemwithonespecificfunction.

o MultiUserOperatingSystem–Anoperatingsystem,whichallowsmultipleuserstousethesystematthesametime.Eachuserisallocatedtheirownrightsanduserfilesarekeptseparate.

o Multi-taskingOperatingSystem–Anoperatingsystemisanoperatingsystemthat

onlymorethanoneprocesstorunsimultaneously.Thisisimplementedusingtime-slicing,whereeachprocessisgivenafixedamountofprocessingtime,beingthenextprocess resumes. Processor is so fast that appears these tasks care carried outsimultaneously.

VirtualMachinesVirtualMachine–Asoftwareprogramthatisabletoperformasifitwereaseparatecomputerandexecutecodeasifitwereaseparatecomputer.Multiplevirtualmachinesmayco-existonasingle“host”computersimultaneously.Thereexist2typesofvirtualmachines:SystemVirtualMachine–Avirtualmachinetoemulateawholeoperatingsystem,withinahostoperatingsystem,byexecutingitsmachinecodeinavirtualisedenvironment.ProcessVirtualMachine(orApplicationVirtualMachine)–AvirtualmachinetoexecuteasingleapplicationinsideahostOS,withinaplatform-independentvirtualisedenvironment.ProcessVirtualMachinewilloftenrunintermediatecode(e.g.JavaVirtualMachine),orexecutecodeonbehalfofaninterpreter(e.g.Python).

IntermediateCode–Partiallycompiledcodethatisnotmachine-specificthatcanberunonanycomputerwiththeappropriatevirtualmachine.Notethatsourcecodeiscompiledtointermediatecodeandtheintermediatecodeiseitherinterpreted.1.2.2ApplicationGeneration

o Utility software – A piece of software that performs a specific task to aid themaintenance and upkeep of a computer system. An example would be a diskdefragmenter.

o ApplicationSoftware–Softwarecreatedfortoperformspecificandusefultasksfortheuser.

o SystemSoftware-Programsthatcontroltheoperationandhardwareofthecomputersystem.

OpenandClosedSoftware

o Open source software – A piece of software for which the source code is freelyavailableforotherstoexamineandamend.

AdvantagesofOpen-SourceSoftware DisadvantagesofOpen-SourceSoftwareLikelytobefree NoguaranteeofqualityCustommodificationscanbemadetothesourcecode

Copiesofthesourcecodecanbemadeanddistributedfreely

AdvantagesofClosed-SourceSoftware DisadvantagesofClosed-SourceSoftwareLikelytobeofhigh-quality SourcecodecannotbemodifiedThereisusuallyacompanywhocanprovidesupportandfixbugs

Likelytocostmoney

Youcannotmakecopiesordistributethesoftware

Compilation

o Lexicalanalysis:o Sourcecodeisusedasinput.o Tokensarecreatedfromindividualsymbolsandfromthereservedwordsinthe

programminglanguage.o Variablesarestoredinasymbolstable.o Redundantcharacterse.g.spacesareremoved.o Whitespaceisalsoremoved.o Errordiagnosticsaregiven.o Codeispreparedforsyntaxanalysis

o Syntaxanalysis:

o Labelcheck,checkwhetheraprocedureorvariableyoureferenceactuallyexistso Checkswhethercontrolstructurese.g.loopsareclosedcorrectlyo Checkifvariableshavebeenassignedillegalvalueso DoesBIDMAS

o Semanticanalysis:

o Makessureavariableisdeclaredbeforeitisusedo Typechecking

Syntaxandsemanticanalysisbothaddmoreinformationtothesymbolstable.

o Codegeneration:o Producesmachinecode.o Thereareseveralinstructionsforeachhigh-levellanguagestatement.Allvariables

aregivenaddresses.o Codeoptimisationiswherecodeismadeasefficientaspossiblee.g.byreplacing

redundantinstructions.o This is to remove the number of instructions, so the size of the executable is

smaller.o Itisalsotoreduceprocessingtime,sotheprogramrunsfaster.

o Assembler-Aprogramthattranslatesassemblycodeintomachinecode.

o Compiler–Atranslatorwhichconvertssourcecodetomachinecodetoproducean

executableprogram.

o Interpreter–Atranslatorthattranslatesonestatementatatime,thenallowsittoberune,beforemovingontothenextstatement.

Compilers InterpretersTranslatesthewholeprogramasaunitandcreatesanexecutableprogram

Translatesonestatementatatimebeforetranslatingthenext

Executableprogramisarchitecturespecific Reportsoneerroranditspositionbeforestopping

Mayreportanumberoferrorsatonce Mustbepresenteachtimetheprogramisrun

Canoptimisecodetoimprovespeed/size Coderunsinavirtualmachine Programrunsmoreslowlydueto

translation Canrunonavarietyofdevicesimproving

portability

o Linker–Usedtocompilepiecesofcodethathavealreadybeencompiledtoproduceasingleexecutablefile.Itdoesthisbydealingwithreferencesfromthemainprogramtoothercompiledmodules.

o Loader–Copiestheexecutablecodeintoprimarymemoryreadyforexecution.

o Library–Acollectioncompiledsectionsofcodethatcanperformusefultasksthatcan

beusedwithinothercomputerprograms.

o Advantagesoflibraryprograms:o Alreadybeentested,solikelytobeerror-freeo Alreadybeenwritten,sosavestimeo Havingbeenwrittenitisreusableo Writtenbyexperts,socodelikelytobemoreefficient

1.2.3SoftwareDevelopmento WaterfallModel–Asequentialdevelopment lifecycle,whereonestage iscompleted

fullybeforemovingontothenextstage.Thereisaheavyemphasisonplanning.Ifyouhavetogobacktoapreviousstage,youhavetorepeatallstagesafterthat.Stagesofthewaterfalllifecycle:

o Requirementso Analysiso Designo Implementationo Testingo Maintenance

AdvantagesoftheWaterfallModel DisadvantagesoftheWaterfallModelSimpleandeasytomanage NospaceforflexibilityWelldefinedboundaries RequirementscannotchangeEasytospotproblemsthatmightcomeup Endusernotconsultedafterrequirementso SpiralModel–Arisk-drivendevelopmentlifecycle,wheredevelopmentisconductedin

a seriesofwaterfallmodel-based iterations. These iterationsendwith aphaseof riskanalysis.

AdvantagesoftheSpiralModel DisadvantagesoftheSpiralModelFocussingonrisk Veryslow Getting someone who can do risk

managementproperlyiscostlyo AgileMethodology–Asetofprinciples fordevelopment lifecycleswhichfocusseson

adaptiveplanning,earlydeliveryandcontinuous improvement.Developmentoccurs inincremental iterations, which create working prototypes. Development can adapt tochangingrequirements,andfeedbackcanbereceivedfromclientsearlyon.

o ExtremeProgramming–Adevelopmentlifecyclewheredevelopmentisconductedisa

series of short cycles each producing a new release, where there is an emphasis ofreceivingcontinuousfeedbackfromtheclient.Thereisalsoanemphasisoffixingbugsearly on e.g. by writing unit tests before programming. Extreme programming alsoemphasisesintegratingandtestingthesystemseveraltimesaday.

AdvantagesoftheExtremeModel DisadvantagesoftheSpiralModelVeryhigh-qualitycode CostsalotVeryefficientcode Requiresregularcontactwithendusero Rapid Application Development – A development life cycle where development is

conducted is a seriesof short cycles eachproducingprototypes. The cycles iterativelyimprovetheprototypetillitbecomesthefinalproduct.Littletimeisspentplanning,asopposedtoprogramming.

AdvantagesoftheRAD DisadvantagesoftheRADUserisinvolved RegularcontactwithclientneededProgramveryspecifictorequirements Notverygoodformassiveprojects Notverygoodifyouneedefficientcodeo Rapid Application Development and Extreme Programming are in essence agile

methodologies.1.2.4TypesofProgrammingLanguages

o Class-Atemplatedefiningmethodsandattributes,thatcanbeinstantiatedtomakeobjects.

o Inheritance-Whereaclassknownasthechildclassorsubclassderivesthemethods

andattributesofaparentclassorsuperclass.Thesubclassmayoverridesomeofthesemethodsandattributes,anddefineitsownadditionalattributesandmethods.

o Assemblylanguage-Aprogramminglanguagethatiscloselyrelatedtothespecific

machinearchitecture,usingmnemonicsforinstructions,andlabelstoallowjumpingtootherinstructions.Eachinstructionistranslatedintoonemachinecodeinstruction.

o Proceduralprogramming–Aprogrammingparadigmwheretheprogramconsistsof

a seriesof instructions that tell the computerwhat todo to solve theproblem. Itconsistsofsequence,selection,iterationandrecursion.Codeiswritteninblocksareproceduresthatcanbecalledatanypointinaprogram’sexecution.

o Object-oriented programming – A programming paradigm where details of the

implementation are abstracted away using structures called classes, that can bereused,toreducetheamountofcodeandmakeprogramseasytomaintain.

o Declarativeprogramming–Aprogrammingparadigmwhereyouwriteastatement

describingtheproblemyouwanttobesolved,butthelanguageimplementationwilldecidehowtosolveit.

o Logicprogramming–Aprogrammingparadigmiswherethereisasetoffactsanda

setofrules,thatareusedtoperformcomputation.

o Functionalprogramming–Aprogrammingparadigmthattreatscomputationastheevaluationofmathematicalfunctionswhichacceptinputandreturnoutput.

Polymorphism–Wheredifferentsubclassesofasuperclasshavedifferentimplementationsofthesamemethod.Encapsulation–Whereattributesofaclassaredeclaredasprivate,sotheycanonlybeaccessedandmodifiedthroughmethods.LMCAssemblyMnemonic InstructionADD AddSUB SubtractSTA StoreLDA LoadBRA BranchalwaysBRZ BranchifzeroBRP BranchifpositiveINP InputOUT OutputHLT HaltprogramDAT DatalocationModesofAddressingMemory

o ImmediateAddressing–Theoperandistheactualvaluetobeoperatedon.o DirectAddressing–Theoperandholdsthememoryaddressofthevaluetobe

operatedon.o IndirectAddressing–Theoperandisthelocation(typicallyaregister)ofthe

memoryaddressofthedatatobeoperatedon.o IndexedAddressing–Thelocationofthedatatobeoperatedonisthecontentsof

theindexregisteraddedtosomeconstantvalue.Anadvantageofindirectaddressingisthatyoucanaccessmorememory.Indexedaddressingisusedwhenmanipulatingarrays.

1.3Data1.3.1Compression,EncryptionandHashing

o LossyCompression -Analgorithmthat reduces the file size to representdata,butaccuracywithwhichitrepresentsthedataislostintheprocess.

o LosslessCompression-Analgorithmthatreducesthefilesizetorepresentdata,such

thattheoriginaldatacanberecoveredwithoutanylossinquality.

o Run-lengthencoding–A losslesscompressionalgorithmwheredata is storedasapieceofdata,e.g.apixelinanimage,followedbyhowmanytimesitisrepeated.Thissavesspacewhenappliedtofileswithlongrunsofthesameitemofdata.

o Dictionarycoding–Alosslesscompressionalgorithmwheredataisencodedusinga

dictionarythatstoressetsofstringsthatcanbefoundinthedata,thestringsinthedataaresubstitutedwithareferencetothepositionofthestringinthedictionary.

o Encryption–Wheredata is transformed fromone form, theplaintext, to another

form,theciphertexttopreventunauthorisedthirdpartiesbeingabletounderstandit. The algorithm used to perform the encryption is called the cipher, and secretinformationtoencodeitiscalledthekey.

o Symmetricencryption–Encryptionwherethesamekeycanbeusedtoencryptand

decryptthedata.

o Asymmetricencryption–Encryptionwheretwodifferentkeysareused.Apublickey,whichismadepublic,isusedtoencryptdatatosendtothepersonwhoproducedthekeys. Theprivate key,which is kept secret by this person, is used todecrypt dataencryptedusingthepublickey.

o Hashing–Ahashingfunctionprovidesamappingbetweenanarbitrarylengthinput

todataofafixedsize.It isone-way,asthereisnowaytoobtaintheoriginal inputfromthehash.Usesofhashing includehashtables,andstoringandauthenticatingpeople’spasswords.

1.3.2Databases

o Database–Apersistentstoreofdata.

o Flat-FileDatabase–Adatabasewheredataisstoredasasingletablesequentiallyinafilewithnostructuredrelationships.

o RelationalDatabase–Adatabasewheredataisstoredacrossmultipletables,with

structuredrelationshipsbetweentables.

o Table–Acollectionofrecords.

o Record–Allthedatastoredaboutasingleentity.

o Field(alsoanattribute)–Asinglepieceofinformationaboutarecord.

o PrimaryKey–Anattributethatuniquelyidentifieseverysinglerecordinatable.

o Foreign Key– A non-primary key attribute in one table that stores values from a

primarykeyattributeofanothertable,thuscreatingarelationshipbetweenthetwotables.

o SecondaryKey–Afieldwhosedataisstoredinanindextoallowfastqueriesinvolving

thefield.AdvantagesofaRelationalDatabase

• Reducesdataredundancy• Improvesdataconsistency• Easiertochangedata• Easiertoadddata• Differentdataaccesslevelsofdata

AdvantagesofaFlatFileDatabase

• SimpleandeasytomanageDataDefinitionLanguage(DDL)–Commandsfordefiningthestructureofadatabasee.g.creating/removing/modifyingtablesandcolumnsDataManipulationLanguage(DML)–Commandsformanipulatingdatawithinadatabasee.g.inserting/removing/modifying/queryingrowsinatableDataDictionary–Afiledefiningthestructureofadatabasee.g.whattablesthereare,whatcolumnsareineachtable,thedatatypeofeachcolumn.DatabaseManagementSystem(DBMS)–Acomputerprogramtointeractwithandmanageadatabasee.g.runningqueries,generatingreports,changingschemata,insertingdata,creatingforms.Onetoonerelationship:

Onetomanyrelationship:

Employee Pension

Manytomanyrelationship:

Manytomanyrelationshipshavetobestoredusinganassociativetable,thatcontainsthetwoentitiesasforeignkeys.NormalisationNormalisation-Theprocessofanalysinghowtomakedatabasesmoreefficientbyusingseparatetablestoreduceredundantdata. AdvantagesofNormalisation Noredundantdata,databaseissmallerinsize Smallerdatabase,soqueriesrunfaster Noredundantdata,meansthereislikelytobebetterdataintegrity

o UnnormalisedForm–Thetablecontainsrepeatinggroupsofdata.

o FirstNormalForm–Thetablecontainsnorepeatinggroupsofdata.Forinstance,in

asinglefieldyoucannothavestored4telephonenumbers,separatedbyacomma.Eachtelephonenumbershouldbestoredinitsownrecord.Ifrecordsaresplit intomultiplerecordsduetoattributescontainingrepeatinggroupsofdata,thenthenewprimarykey isacompositekeyconsistingoftheoriginalprimarykeyfield,andtheattributes,thatcontainedtherepeatinggroups.

o SecondNormalForm–Therearenopartialkeydependencies,i.e.thereisnoattribute

thatonlydependsonpartoftheprimarykey.Ifthisisthecase,thenthefieldsthatonlydependonpartoftheprimarykey,shouldbemovedintotheirowntable,wheretheprimarykeyisthepartoftheoriginalkeythattheydependon.Then,aforeignkeyneedstobeaddedtotheoriginaltable,inplaceofpartoftheprimarykey.

o ThirdNormalForm–Therearenonon-keydependencies,i.e.therearenofieldsthat

dependonan itemofdatathat isnottheprimarykey. Ifthisdoesoccur,thenthefieldsshouldbemovedintotheirowntable,wherethefieldtheydependonbecomestheprimarykey.Thenaforeignkeyneedstobeaddedtotheiroriginaltable,inplaceofthedependentkeythatwasmovedtoitsowntable.

Query MeaningSELECT * FROM people Getalltheinformationabouteverybody

storedinthedatabase.

Company Employee

Company Customer

SELECT name FROM people Getthenameofeverybodystoredinthedatabase.

SELECT name, age FROM people Getthenameandageofeverybodystoredinthedatabase.

SELECT * FROM people WHERE name = “Hashan”

GetalltheinformationabouteverybodycalledHashaninthedatabase.

SELECT * FROM people WHERE name = “Hashan” AND age = 18

GetalltheinformationabouteverycalledHashanandwhoseageis18.

SELECT * FROM people WHERE age > 10 AND age < 60

Getalltheinformationaboutpeoplewhoseageisbetween(exclusive)10and60.

SELECT * FROM people WHERE age >= 10 AND age <= 60

Getalltheinformationaboutpeoplewhoseageisbetween(inclusive)10and60.

SELECT * FROM people WHERE age != 18 OR name = “Hashan”

GetalltheinformationabouteverybodycalledHashanorwhoseageisnot18.

SELECT * FROM people WHERE age != 18 OR name LIKE “%Hashan”

Getalltheinformationabouteverybodywhoseageisnot18orwhosenameendswith“Hashan”.

SELECT * FROM people WHERE age != 18 OR name LIKE “Hash%an”

Getalltheinformationabouteverybodywhoseageisnot18orwhosenamebeginswith“Hash”andendswith“an”.

SELECT * FROM people WHERE pet_name IN (SELECT name FROM dog)

Selecteveryfieldofeveryrecordfromatablecalledpeople,wherethevalueofpet_nameisanitemthatalsohappenstobeanameofarecordindog.

SELECT * FROM people WHERE pet_name IN (SELECT name FROM dog WHERE breed = “Rottweiler”)

Selecteveryfieldofeveryrecordfromatablecalledpeople,wherethevalueofpet_nameisanitemthatalsohappenstobeanameofarecordindogwherethebreedis“Rottweiler”.

SELECT people.name, pet.breed FROM people JOIN pet ON people.pet_name = pet.name

Selectsthefield’snamefrompeopleandbreedfrompet,joiningtherecordstogetherwhenthevalueofpet_namefromarecordfrompeoplehasthesamevalueasthevalueofnamefromarecordfrompet.

SELECT people.name, pet.breed FROM people JOIN pet ON people.pet_name = pet.name WHERE name = “Hashan”

Selectsthefield’snamefrompeopleandbreedfrompet,joiningtherecordstogetherwhenthevalueofpet_namefromarecordfrompeoplehasthesamevalueasthevalueofnamefromarecordfrompet.Thenamealsohastobe“Hashan”.

DELETE FROM people Deleteeveryrecordthatexistsintablepeople.

DELETE FROM people WHERE name = “Hashan”

Deleteeveryrecordthatexistsintable,wherenameis“Hashan”.

INSERT INTO people (name, age) VALUES (“Hashan”, 18)

Insertarecordintothetablepeople,withnameassignedto“Hashan”andageto18.

INSERT INTO people (name) VALUES (“Hashan”)

Insertarecordintothetablepeople,withnameassignedto“Hashan”.

DROP TABLE people Completelydeleteatableincludingthedataitcontains.

o DataIntegrity–Thisiswheredataisstoredundertheconstraintsofthedatabase,e.g.thevaluesofrecordsarethecorrecttypeandvalidationrulesareadheredto.

o ReferentialIntegrity–Thisiswhereeverypieceofdatastoredunderaforeignkeyreferstoanotherrowthatexistsinanothertable.

Transactions,ACID,RecordLocking,RedundancyOperationstomodifyadatabasearecarriedoutintransactions.Transactionsisoneormorechangesthataretobemadetoadatabase.Asingletransactioncancontainchangestodifferenttables.Theymustadheretothe4properties:

o Atomicity–Atransactionisprocessedinitsentiretyornotatall.Thismeanseverychangehastomade,ornoneofthechangesaremade.

o Consistency–Notransactioncanviolateanyofthevalidationrulesformaintainingtheintegrityofthedatabase,thisincludesreferentialintegrity.

o Isolation–Thetransactioniscarriedoutindependently,andeachtransactionshouldnotaffectothertransactions.

o Durability–Onceatransactionhasbeencommitted,itremainsso,evenintheeventofapowercut.

o Record Locking – A technique of preventing simultaneous access to objects in a

databasetopreventinconsistentresults.Thisiswherearecordislockedwhenitistobe updated, so that nobody else can access the same record, until the update isfinished.

o Redundancy–Thisiswheretwoormoreidenticaldatabasesystemsaremaintained

indifferentgeographicallocations,sothateverytransactionisappliedtoalldatabasesystems.Intheeventofonesystemfailing,othersystemscantakeover.

1.3.3Networks

o LocalAreaNetwork–Agroupofcomputerslinkedtogetheroverasmallgeographicalarea.

o Wide Area NetworkA group of computers over geographically remote distances,usuallyconnectedthroughthird-partycommunicationlinks.

CharacteristicsofLAN

- Smallgeographicalarea- Moresecure- Hard-wiredorshort-rangewireless

CharacteristicsofWAN

- Datavulnerabletointerception- Geographicallyremotedistances- Tendstousethird-partycommunicationlinks

Client-ServerNetwork-Oneormorenodesactasacentralserverwhichcentrallystoresdataandmanagesthenetwork,whiletherestareclients,whichrelyontheserver.Peer-to-PeerNetwork -Nonode is inoverall control,eachcansharedataandconnectedperipheralstoothersbasedonasetofaccessrights.AdvantagesofClient-Server DisadvantagesofClient-ServerFiles are stored in a central location, anddifferentuserscanbegivendifferentaccessrights

Adedicatednetworkmanagerisneeded

Peripherals, backups and security can becontrolledcentrally

Serversareexpensive

Software licenses and installation can becontrolledcentrally

If the servers fails, noneof the clientswillfunction

AdvantagesofPeer-to-Peer DisadvantagesofPeer-to-PeerEasiertosetupthanClient-Server Files are disparate, stored across multiple

machinesmakingthemdifficulttolocateIfonenodefails,othernoeswillstillfunction Backups and security cannot be controlled

centrally, so it is the responsibilityof eachusertoproperlybackupandsecurehis/hercomputer

Noneedforadedicatednetworkmanageroradditionalnodes,toactasaserver

ProtocolsProtocol–Asetofrulesthatgoverncommunicationinanetwork.ThelayersoftheTCP/IPmodelcansplitintothefollowing:

• ApplicationLayer(e.g.HTTP)–Encodesthedatabeingsent.• TransportLayer(e.g.TCP)–Splitsthedataupintopackets,assignspacketheaders

andaddsportnumber.• NetworkLayer(e.g.IP)–Addsthesender’sandtherecipient’sIPaddress• NetworkAccessLayer(e.g.EthernetorWi-Fi)–AddsMACaddressinformationto

specifywhichhardwaredevicethemessagecomesfromandisgoingto.IPAddress–Anaddressassignedtodevicestoindicatewhereapacketofdataistobesentorhasbeensent from.Routersareassigned IPaddresses fromInternetServiceProviders.ThesearepublicIPaddressesandareuniqueacrosstheinternet.RoutersprovideprivateIPaddresses to computers within a network. Private IP addresses are only uniquewithin anetwork.

FeaturesoftheIPProtocol• Addingthesender’sandtherecipient’sIPaddress

FeaturesoftheTCPProtocol

• Allocationofportnumbers• Splittingdataintopackets• Retransmittingpacketsiftheywerelostintransmit• Checkingdatawhetherdatahasbeenchangedduring transmit,andattempting to

correctitifithas(i.e.errorcorrection)FeaturesoftheDataLinkLayer

• AddingtheMACaddressAdvantagesofprotocollayering

• Higherlevelprotocolsdonothavetoworryabouttheimplementationdetailsoflowerlevelprotocolsandviceversa

• Higherlevelprotocolscanoftenworkontopofmultiplelowerlevelprotocolse.g.IPpackets can be sent on Ethernet,which requires IP to run on top of the Ethernetprotocol,orIPcanbesentonWi-Fi,whereinIPrunsontopoftheWi-Fiprotocol.

• Abletocodeforspecificlayers.Disadvantagesofprotocollayering

• Overheadduetoamessagehavingtopassthroughmultiplelayers,increasingpacketsizes.

MAC(MachineAddressCode)address -Auniquehardwareidentifierfordevicesthatcanconnecttoanetwork,consistingof48bitsofdata.AMACaddressisusuallybuiltintotheNICofacomputer.NotwodeviceswilleverhavethesameMACaddress.URLstandsforUniformResourceLocator.Inawebaddress,httpistheprotocol.wwwisthehost.www.bbc.co.ukisafullyqualifieddomainname.ukisthetop-leveldomainname.Thepathis/news.NetworkHardwareHub-Ahardwaredevicethatconnectstogethermultiplenodesinanetwork.Ahubbroadcastsallthedatareceivedfromoneporttoalltheotherports,regardlessoftowhomthepacketsareaddressed.Thisusesupalotofunnecessarybandwidth.Bridge-Ahardwaredevicethatconnectstogethertwonetworks,suchthattheyactasaonelargernetwork.Abridgecheckstoseeiftherecipientofamessageisontheothernetworkbeforerelayingapacket.Switch-Ahardwaredevicethatconnectstogethermultiplenodesinanetwork,butratherthanbroadcastingalldata,checkstheMACaddressoftherecipientandsendsittothecorrectnode,asopposedtoallthenodes.

Modem-Ahardwaredevicethatconvertstoandfromdigitaldatathatacomputernetworkusestoandfromanaloguesignalsthattelephonenetworkuses.WirelessAccessPoint(WAP)-Ahardwaredevicethatallowswirelessdevicestoconnectandaccessthenetworkbyrelayingconnectionsthroughtothehard-wirednetworktheWAPisconnectedto.Router-AnetworkdevicethatcanformaLANbyconnectingnetwork-capabledevicestogether,andchoosesthenodetoforwardpacketssuchthatpacketsfollowthefastestroutepossible.Repeater-Anetworkdevicethatreceivesdegeneratedsignalsandsendsthem“regenerated”,inordertopreventsignalsdegeneratingtoomuchsuchthattheycannolongerbeunderstood.DNSDomain Name System – The system by which human-readable domain names (e.g.google.com)areconvertedintothecorrespondingIPaddresses.ADNSservermapsadomainname into an IP address. If it cannot resolve the domain name, it recursively passes therequesttoanotherDNSserver,untiltheIPaddressisfound.WhyisDNSused?

o BecauseIPsarehardtoremember.o BecauseIPscanchange.

NetworkSecurity

o Malware–Aprogramdesignedtodisrupt,damageorgainunauthorisedaccesstoacomputersystem.

o Firewall–Apieceofsoftwareorhardwarethatinspectspacketsagainstasetofpreconfiguredrulescalledpacketfilters,todecidewhetherthepacketshouldbeallowedthrough.

o ProxyServer–Aproxyserverinterceptsallpacketsenteringandleavinganetwork,hidingthetruenetworkaddressofthesourcefromtherecipient.Thisenablesprivacy.Aproxycanalsobeusedtofilterrequeststocontrolthecontentthatuserscanaccess.Itcanalsobeusedtomaintainacacheofcommonlyrequestedwebsitestosavetime.

o Encryptioncanalsobeusedtokeepmessagestravellingacrosstheinternetsecure.PacketandCircuitSwitchingPacketSwitching CircuitSwitchingNoestablishedroute Establishesaroutealongwhichtosend

packetsforthedurationofthemessagePacketsaresentonindividualroutes PacketsallfollowthesamerouteSecurebecauseimpossibletointerceptallpackets

Becauseofallpacketsfollowthesameroute,easytointercept

Packetsneedtobereassembled Packetsremaininthecorrectorder

Maximisestheuseofnetwork Tiesuplargeareasofthenetwork1.3.4WebTechnologiesHTML,CSSandJavaScriptBasicElementsOneShouldKnow:Element Attributes<html> <head> <title> <body> <h1> <h2> <h3> <a> href<div> <form> <p> <li> <ol> <ul> <script> name, type=”text”, type=”submit” ElementsThatDoNotRequireaClosingTag:Element Attributes<link> href, rel, type<img> src, alt, height, width<input> The only other attribute that one needs to know is the style attribute for all applicableelements.Thisisusedforinlinestyles.Inlinestylesarebadbecause:

o Createredundantcode.o Morecode,meansloadsslower.o Difficulttomaintain.

External styles arewhere they are rewritten in a different file and linkedwith a link tag.Advantagesaretheoppositeofthedisadvantagesofinlinestyles.CSSPropertiesThatOneShouldKnow:Propertybackground-color border-colorborder-style

border-width font-family font-size height width OneshouldknowhowtouseCSSidentifierswithids,classesandtagnamesaswellasCSSnamedandhexadecimalcolours.OneshouldknowhowtousetheJavaScriptfunctions, and.OneshouldalsoknowoftheinnerHTML propertyofelements.JavaScript Descriptiondocument.getElementById Methoddocument.write Methodalert MethodinnerHTML PropertyofanelementSearchEngineIndexingSearchenginesmaintainanindexofallpagesontheinternet,whichyourqueryiscomparedto.Queryingan index isdesignedtobevery fast.The index iscontinuallyupdatedby thesearchengineindexingalgorithm,byremovingpages,addingnewones,orupdatingtherankofeachpage.Aspiderisusedbythesearchenginetocrawlbetweenpages,andindexeverypageitfinds.Itchecksmetatags,whichcontaindataaboutthewebpage,andfollowsallofthelinksonapageinordertocollectdataaboutapage.Themorelinksapagehas,andthehigherthequalityofthoselinks,thehigherrankedapageisintheindex,sotheeasieritistofindwithaquery.Client-sideandServer-sideprocessingAsthenamesuggestsclient-sideprocessingiswheredataisprocessedontheclientinthewebbrowser,usuallyusingJavaScript.Server-sideiswherethedataissenttotheservere.g.throughaHTMLform,forprocessing.Client-sideprocessing Server-sideprocessingInitialdatavalidation FurtherdatavalidationCanappliesCSSstyles PerformsdatabasequeriesandupdatesReducestheloadontheserver Performscomplexcalculations EncodesdatatoreadableHTMLClient-side validation can be bypassed e.g. by forging server-side requests, so server-sidevalidationalwayshastobeimplemented.So,ifyoudoimplementclient-sidevalidation,youstillnedtoimplementserver-sidevalidation.

1.4 DataTypes1.4.1DataTypeso Primitivedatatype–Adatatypebuiltintoaprogramminglanguage.

o Oneshouldbeawareofintegers,floatingpointnumbers,characters,stringsand

Booleans.PositiveBinaryIntegersAlldatainacomputersystemisstoredasacollectionof0sand1s,knownasbinary.Thewaymeaningfuldatabeitnumbersorcharactersareencodediscalleddatarepresentation.Binarycanbeeasilyusedtorepresentnumbersasallitisinessenceisanumericalsystem,exceptwithonlywiththedigits0and1.Thenumericalsystem,humanshavecometonaturallyuseiscalleddenaryorbase10,asituses10digits(0-9).Binaryorbase2workssimilarlytodenary.Likeindenary,0inbinaryrepresents0.Similarly,1inbinaryrepresents1indenary.However,since2isnotadigitinbinary,torepresent2inbinary,10isused.Thesameprincipleoperatesindenary,whenallthecombinationsofdigitspossiblehaverunout,anadditionalcolumnisused.So,3inbinaryis11,andafterthat,sincetherecannotbea12,toexpress4,100isused.Toexpress5,101isused,for6,110isused,7,111.Andthenfor8,anothercolumnmustbeadded,soweget1000.Youmayhavenoticeditwaswhenwegotto2,4,8, that itbecamenecessary toaddanothercolumn.Thesamecontinues,1000 inbinaryrepresents8,10000represents16,100000represents32.Thisbecausetheyarethepowersof2(21=2,22=4,23=8,24=16,25=32,26=64,etc.).Thesamehappensindenary,exceptratherthanthepowersof2,itisthepowersof10(10,100,1000).Inprimaryschool,youarelikelytohavebeentaughttothinkofnumbersintermsoftheunits,tens,hundreds,thousands,column,etc.ExampleTowrite563indenarycolumns,youwouldwrite:

100s(102)

10s(101)

1s(100)

5 6 3Notethat(5*102)+(6*101)+(3*100)=563.Thesameprinciplesapplytobinary.ExampleForexample,toconvertthebinarynumber101011todenary,youwouldwriteitoutasfollows:

32s(25)

16s(24)

8s(23)

4s(22)

2s(21)

1s(20)

1 0 1 0 1 1Thenyouwouldmultiplyeachdigitbyitsrespectivevalue,andadduptheresults.Sohereyouwoulddo(25*1)+(24*0)+(23*1)+(22*0)+(21*1)+(20*1),whichequals43.

Infact,sincetheonlydigitsinbinaryare0and1,theprocessallyouactuallyhavetodoitlookforthedigitswhichare1s,andaddtheirrespectivevaluestogether,sohereallyouwoulddois32+8+2+1,whichequals43.Youmayhaverealisedthatabinarynumberwillonlybenegativeifthefinaldigitis1,asthefinaldigitistheonlynumberwithanoddcolumnvalue.In the exam, theywill be likely to talk about 8-bit binary, i.e.where binary numbers areallotted8bitsofspace.Ifyouaregivenan8-bitbinarynumberthatonlyuseslessthan8digitsforexampleitwillhaveleading0stomakeupforit.ExampleSo,1011,wouldbewrittenas00001000for8-bitbinary.Thisiswhathappensincomputermemoryaswell.Numbersareallottedasetnumberofbits,andiftheyuselessthen,thebitswhicharenotused,aresetto0.Thisalsomeansinyourexam: youwill have tomake sure that if you are giving an answer, youput the requiredamountofleading0s.Thesameprincipleappliesto16-bitbinaryetc.So,toconvertfromadenarynumberto8-bit-binaryyouwoulddrawoutatable,likebeforewith8columnsfrom27to20,andyouwouldlookateachcolumnvaluefromlefttoright,toseeifitissmallerthanorequaltothenumberinquestion.Ifitisnot,youwrite0.Ifitisyousubtractthecolumnvaluefromthenumberinquestion,andwrite1inthatcolumn.ExampleLetusconvert42into6-bitbinary.Wewoulddrawoutatablefrom25to20.

32s(25)

16s(24)

8s(23)

4s(22)

2s(21)

1s(20)

32≤42,sowedo42–32=10.Andwewrite1inthe32scolumn.

32s(25)

16s(24)

8s(23)

4s(22)

2s(21)

1s(20)

1 However,16>10,sowewrite0inthe16scolumn.8≤10,sowedo10–8=2.Andwewrite1inthe8scolumn.2

32s(25)

16s(24)

8s(23)

4s(22)

2s(21)

1s(20)

1 0 1 Again4>2,sowewouldwrite0inthe4scolumn.But2≤2,sowewouldwrite1inthe2scolumn.Thenwedo2–2=0.Thenwewouldwrite0inthe1scolumn.

32s(25)

16s(24)

8s(23)

4s(22)

2s(21)

1s(20)

1 0 1 0 1 0

Hexadecimalisanothernumericalsystem,butwith16digits:0-9makeupthefirst10digits,andthelettersA-Fmakeupthenext6.So,inhexadecimalA16=1010andB16=1110,andsoon.Hereisatablecomparingbinary,denaryandhexadecimal.

Binary Denary Hexadecimal0000 0 00001 1 10010 2 20011 3 30100 4 40101 5 50110 6 60111 7 71000 8 81001 9 91010 10 A1011 11 B1100 12 C1101 13 D1110 14 E1111 15 F

Becausebinaryisbase2andhexadecimalisbase16,and24=16,asetof4binarydigitscanberepresentedby1hexadecimaldigit.Youcanusethistoconvertfrombinarytohexadecimalandviceversareallyeasily.Toconvertfrombinarytohexadecimal,drawtheabovetable,converteachblockof4binarydigitstoitscorrespondinghexadecimaldigit.Toconvertformhexadecimaltobinary,converteachhexadecimaldigittoitscorrespondingblockof4binarydigits.Convertingfromdenarytohexadecimalandhexadecimaltodenaryiseasyaswell,asyoucanusebinaryasanintermediarybase.Forexample,toconvertfromdenarytohexadecimal,gofromdenary→binaryandbinary→hexadecimal. SignandMagnitudeo Signandmagnitudeisawayofrepresentingintegers,wherethefirstbitisasignbit.Ifit

is0,theintegerispositive,otherwisetheintegerisnegative.ExampleToconvert-8to8-bitsignandmagnitudebinary,firstwriteitnormally,i.e.00001000.Then,becauseitisnegativewemakethemostsignificantbit1.Sowehave10001000.

o Problemswithsignandmagnitude:

o Thereare2differentrepresentationsof0.o Additionandsubtractionaremorecomplicated.

Two’sComplemento In two’s complement the leftmost bit represents a negated version of what it would

normally.Forinstance,inthecaseof8-bitbinary,thiswouldmeantheleftmostbitwouldrepresent-128.

ExampleSayyou’regiven1010,becausewe’redoing4-bitbinary,themostsignificantbitis1,andthatisworth-23,soitisworth-8.Thentheonlyotherbittoconcernourselveswithisthesecondfromtheright,whichisworth21,sowedo-23+21,toget-6.o Tonegateatwo’scomplementnumber,invertthebitsandaddone.ExampleSayyou’regiven0100andyouneedtonegateit,firstyouinvertthebitstoget1011.Thenyouaddonetothenumbertoget1100.o Toaddtwo’scomplementnumberstogether,yousimplydonormallybinaryaddition.If

theadditionof twopositivenumbers yields anegativenumber, thenanoverflowhasoccurred.Iftheaddition,oftwonegativenumbershasyieldsapositivenumber,thenanoverflowhasoccurred.Otherwiseanoverflowhasn’toccurred.

ExampleForinstance,toadd-3and5using4-bit2’scomplement,firstwritethemout.Toobtain,-3firstnegate3,whichis0011.Thisgivesyou1101.5isjust0101.Thensimply,add1101+0101=10010.Noticethatthereisanoverflow.Orsoitappears.Butnoneofourruleshavebeenviolated.So,wesimplyignorethefinalbit,andwearriveat0010.Noticethisis2.Funnilyenough-3+5is2.o To subtract two’s complement numbers, simply negate the second and add them

together.o An important thing to bear inmind is that if you have a negative two’s complement

number,e.g.1111,thenitisnotthesamethingas01111.Itis,however,thesamethingas11111.Thesameappliestotwo’scomplementnumbers.0111,isnotthesamethingas111,butitisthesamethingas00111.

o Thesameappliestheotherway.Ifyouhave00111,thisisclearlythesameas0111.Ifyou

have1111,thisisthesameas1.

ExampleLetussaywewanttoadd11and0101,andbothofthemarealreadytwo’scomplementnumbers.Thenwemustmake11into1111.Thenweperformtheaddition,toget10100.What just happened? Anapparentoverflow! But because none of our two ruleswereviolated,wesimplyignorethenewbit,toget0100.Two’sComplementFloatingPointNumberso Usesoffloatingpointnumbers

o Tostoredecimalnumberso Tostoreverylargeorverysmallnumbers

o Floatingpointnumbersarerepresentedusingamantissafollowedbyanexponent.o Infloatingpointbinary,themantissaisadecimalwherethedecimalpointisafterthefirst

bit. Since the firstbitbefore thedecimalpointhas thevalue20, the firstbitafter thedecimalpointhasthevalue2-1,andsoon.

ExampleSupposeourmantissais0101.Addingthedecimalpointgives0.101.Addingthevalueofbitsgives2-1+2-3whichis5/8.So,5/8isthevalueofthemantissa.o Thevalueofthenumberisthemantissamultipliedby2tothepoweroftheexponent.

Notethatmultiplyingby2,istheequivalentofshiftingtotheleftbyacertainnumberofplaces.So,itisjustthemantissashiftedtotheleftbythenumberoftimesrepresentedbytheexponent.

ExampleSupposeourmantissais0101.Addingthedecimalpointgives0.101.Addingthevalueofbitsgives2-1+2-3whichis5/8.So,5/8isthevalueofthemantissa.Letusnowsaythevalueoftheexponentis0101.Thisis5indenary.So,theweshiftthemantissaby5 to the left,oralternatively thedecimalpoint,or radixpoint incomputerscience,totherightby5.Thisgivesus010100.Thevalueofthenumberis20.o Notethatthemantissaandexponentarestoredintwo’scomplementbinary,soifthe

exponentisnegativethenthemantissaisshiftedtotheright.o ExampleSupposeourmantissais0101.Addingthedecimalpointgives0.101.Addingthevalueofbitsgives2-1+2-3whichis5/8.So,5/8isthevalueofthemantissa.Letusnowsaythevalueoftheexponentis1101.Thisis-3indenary.So,theweshiftthemantissaby3totheright,oralternativelythedecimalpoint,orradixpointincomputerscience,totheleftby3.Thisgivesus0.000101.Thevalueofthenumberis2-4+2-6whichis5/64.

o Thevalueofthemantissaisabinarynumber,butwherethedecimalpointisafterthefirst

bit.Forinstance,ifthemantissais0101,thenitactuallyrepresents0.101.Thevaluesofthebitsafterthedecimalpoint,followthesamepatternasthevaluesofthebitsbeforethedecimalpoint.So,thevalueofthefirstbittotheleftofthedecimalpointis20,sothevalueofthefirstbittotherightis2-1,i.e.½.

o Theexponentisjustaregulartwo’scomplementExampleLetususea4-bitmantissaanda4-bit exponent. Letususe two’s complement for themantissaandtheexponent.Letthemantissabe0100.Theonlybitthatis1isthesecondfromtheleft.Thisisworth2-1,i.e.a½.Letussaytheexponentis0010.Thismeansitis2.Wedo½*22,toobtain2.ExampleLetususea4-bitmantissaanda4-bit exponent. Letususe two’s complement for themantissaandtheexponent.Letthemantissabe0100.Theonlybitthatis1isthesecondfromtheleft.Thisisworth2-1,i.e.a½.Letussaytheexponentis1010.Thismeansitis-6.Wedo½*2-6,toobtain1/64.o A normalised floating-point number should beginwith two different digits. A positive

numbershouldbeginwith01,andanegativenumbershouldbeginwith10.ExampleLetususea4-bitmantissaanda4-bit exponent. Letususe two’s complement for themantissaandtheexponent.Letthemantissabe0010.Theonlybitthatis1isthethirdfromtheleft.Thisisworth2-2,i.e.a¼.Letussaytheexponentis1010.Thismeansitis-6.Wedo¼*2-6,toobtain1/128.Notice,thatthisisnotanormalisednumberbecausethefirsttwodigitsofthemantissaarethesame.Toremedythis,weshiftthedigitsofthemantissatotheleftby1.Thisisequivalenttomultiplyingby2.So,wemustdecrementtheexponentby 1,which is the equivalent of dividing by 2. So, the newmantissa is 0100. The newexponentis1001.Noticethisisstillequivalentto1/128.ExampleLetususea4-bitmantissaanda4-bit exponent. Letususe two’s complement for themantissaandtheexponent.Letthemantissabe1101.Thisisequivalentto-3/8.Letussaytheexponentis0101.Thismeansitis5.Wedo-3/8*25,toobtain-12.Notice,thatthisisnotanormalisednumberbecause the first twodigitsof themantissaare thesame.Toremedythis,weshiftthedigitsofthemantissatotheleftby1.Bywewanttopreservethenumbersign.So,wedon’tmodifythefirstbit.Thisisstillequivalenttomultiplyingby2.And,wemustdecrementtheexponentby1,whichistheequivalentofdividingby2.So,thenewmantissais1010.Thenewexponentis0100.Noticethisisstillequivalentto-12.o Addingandsubtractingfloatingpointsnumbersisperformedbymakingtheexponentthe

same.Thenperformingnormaladditionandsubtraction.

ExampleLetusadd0.5and6.Innormalisedtwo’scomplementfloating-pointbinarywith6bitsforthemantissaandexponenttheseare:0.5–0100000000006–011000000011Firstyouaddthedecimalpointandshiftthenumbers,bytheexponent.So,thefirstnumberstaysthesameas0.1,andthesecondnumberbecomes0.11*23=0110.Thenaddthenumbers0.1+0110=0110.1.Thenshiftthedecimalpoint,backsothenumberisnormalised,soyouhave0.1101.So,themantissais011010.Sinceyoushifteditby3,theexponentis3,i.e.000011.Thatmakes6.5.o Ifyouaredoingthiswithatwo’scomplementmantissa,thenyouneedtoknowthatto

convertapositivetwo’scomplementnumberofsay4bits,tooneof8bitsyousimplymaketheleftmost4bits0.Todothisforanegativetwo’scomplementnumber,youmaytheleftmost4bits1.

ExampleLetusadd-0.5and6.Innormalisedtwo’scomplementfloating-pointbinarywith6bitsforthemantissaandexponenttheseare:-0.5–1000001111116–011000000011Firstyouaddthedecimalpointandshiftthenumbers,bytheexponent.So,thefirstnumberisshiftedtorighttobe1.1,andthesecondnumberbecomes0.11*23=0110.Thenaddthenumbers1.1+0110.Thisgivesyou1111.1+110=10101.1.Anoverflowappearedtohaveoccurred,soyouignorethelastbit,soyouhave0101.1.Thenshiftthedecimalpoint,backsothenumberisnormalised,soyouhave0.1011.So,themantissais010110.Sinceyoushifteditby3,theexponentis3,i.e.000011.Thatmakes5.5.BitwiseManipulation

o AbitwiseAND,ORorXORiswheretheappropriatelogicgatesareappliedtoeachcorrespondingbitonapairofnumbers.

o Logicalshiftsshiftthenumberleftorrightandmakethevacatedbit0.o Arithmeticshiftsshiftthenumberleftorrightbutkeepthesignbitthesame.When

shiftingright,thisisdonebymovinga1intothevacatedbitifthesignbitwas1.Ifshiftingleft,thentheshiftignoresthesignbit.

o Circularshiftsshiftthebitsinacircle.CharacterSet

o CharacterSet-Thesymbolsacomputersystemcanrecognise.Normallycorrespondstosymbolsonakeyboard.Eachsymbolhasanumericvalue.ExamplesincludeASCIIandUnicode.

1.4.2DataStructuresArray–Astaticdatastructureconsistingofalistofvalues,ofthesamedatatype,storedcontiguouslyinamemorylocationaccessiblefromasingleidentifierwithanindex.LinkedList–Adynamicdatastructureconsistingofnodeswhichconsistofdataandapointertothenextnode.AdvantagesofArrays AdvantagesofLinkedListsDataisstoredcontiguously,soaccesstimesareconstanti.e.arraysallowrandomaccess

Linkedlistsaredynamicdatastructures,soasmanyitemsasnecessarycanbeadded

Lessoverheadasnopointersstored Easier to move items around and deleteitems,asonlypointers,needtobechanged

Merging two linked lists is easier, as thepointer from the finalnodeof the first listjustneedstobesettothefirstnodeofthesecond.

Record–Acollectionofnamedfields,whichmaybeofdifferentdatatypes,thatarestoredinamemorylocationtogetherunderasingleidentifier.Toaccessanindividualfield,therecordidentifierandthefieldnameareusedinconjunction.Tuple–Atupleisanimmutablecollectionofvalues,whichmayofdifferentdatatypes,storedunderasingleidentifier.Toaccessanindividualfield,anindexisused.Queue-Afirst-in-first-out(FIFO)datastructure,wherethefirstitemtobe“enqueued”(addedtothequeue)isthefirstitemtobe“dequeued”(removedfromthequeue).Stack-Alast-in-first-out(LIFO)datastructure,wherethelastitemtobe“pushed”(addedtothestack)isthefirstitemtobe“popped”(removedfromthestack).Astackhasapointertothelastitem,aqueuehasapointertothefirstandthelastitem.Queuesandstackscanbeofafixedcapacity,i.e.static,orofavariable-length,i.e.dynamic.Graph–Agraphisadatastructureconsistingofasetofvertices(ornodes)connectedbyedges(orarcs).UndirectedGraph–Agraphwherealledgesarebidirectional.DirectedGraph–Agraphwherealledgesareone-way.Tree-Adatastructuremadefromnodeswhichcanhaveanumberofchildren,whicharealsonodes.Anodecanonlyhaveonparent,exceptfortherootnodewhichhasnoparent.BinarySearchTree–Atreewhereeachnodecanhaveamaximumoftwochildren,wherenodesarestoredinanorder,byhavingthenodesintheleftsubtreebelessthanagivennode,andthenodesintherightsubtreegreaterthan.

Pre-ordertraversal–Thecurrentnodeisvisitedbeforeitsleftsubtreeanditsrightsubtreearerecursivelytraversed.In-ordertraversal–Theleftsubtreeofanodeisrecursivelytraversed,beforethecurrentnodeisvisited,andthentherightsubtreeisrecursivelytraversed.Post-ordertraversal–Theleftsubtreeandrightsubtreeofanodeisrecursivelytraversed,beforethecurrentnodeisvisited.HashTable–Adatastructurewhereitemsofdataareaccessedbykeys.Thedataisstoredinbuckets. To decidewhich bucket should hold a piece of data identified by a given key, ahashingalgorithm isapplied to thekey toget the indexofaparticularbucket.Acollisionoccursiftwokeysaretobestoredinthesamebucket.Onewayofresolvingthisisstoringlinkedlistsineachofthebuckets. ApplicationsofQueues

• StoringjobstobeprocessedbytheCPU• Storingrequeststoawebsiteoradatabasetobeprocessed

ApplicationsofStacks

• Callingfunctions(argumentsstoredinastack)• Manyprogramminglanguagesusestackstoparsecodewhencompiling/interpreting

1.4.3BooleanAlgebraOperation Symbol Gate

AND A�B

OR A�B

NOT ¬ A

XOR A�B

Youalsoneedtobeawarethat:A≡BmeansthattheBooleanexpressionAisequivalenttotheBooleanexpressiontoB.SimplifyingBooleanExpressions

BasicLaws

A�1≡1A�0≡AA�1≡AA�0≡0

DoubleNegationLaw ¬¬ A ≡A

IdempotentLaws A�A≡A A�A≡A

ComplementLaws A�¬A≡1A�¬A≡0

DistributiveLawsA�(B�C)≡(A�B)�(A��C)A�(B�C)≡(A�B)�(A��C)

DeMorgan’sLaws¬(A��B)≡(¬A��¬B)¬(A��B)≡(¬A��¬B)

ANDandORarealsocommutativeandassociativeoperations.KarnaughMapsKarnaughMapsareanalternativewayofsimplifyingBooleanexpressions.This isdonebycreatingatable,wheretherowsareonevariableandthecolumnsareanothervariable.IfdoingKarnaughmapson three-variable, four-variableproblems,orevenbiggerproblems,then one writes multiple variables as the columns/rows. For instance, if A, B and C arevariables, thenAmightbetherows,andBCmightbethecolumns.Eachrowandcolumnrepresentsacertainassignmentofvariablesofasubsetofthevariables.Eachcellrepresentsacompleteassignmentofvariables,andstoreswhattheexpressionwouldevaluatetointhatcase. It isessential thatthevariableassignmentsthattherowsorcolumnsrepresentonlydifferby1bit.Thenoneselectsthebiggestgroupsof1,2,4,8,etc.onesthatformarectangle.Therectanglemaywraparoundtheedges.Thenonefindstheexpressionthatmakethesegroups1andcombinesthenusingOR.AddersandD-TypeFlipFlops

o HalfAdder–Ahalfaddertakestheinputoftwobitsandgivesatwo-bitoutput,consistingofasumandacarry.

o FullAdder–Afulladderismadefromtwohalfadderstoaddthreebits,whereoneofthebitsisacarry.Itproducesatwo-bitoutput.

o Toconstructanaddercapableofaddingtwon-bitnumbers,simplycombinenfulladders.

o D-TypeFlipFlop–Aflipflopisacircuitthatcanstoreonebit.Ithastwoinputs,acontrolinputandaclocksignal.AD-typeflipflopisapositiveedge-triggeredflip-flop;thismeansthatittakesthevalueswhenevertheclocksignalchangesfrom0to1,andthisistheonlytimeitdoesthis.

1.5 Legal,moralandethicalissues1.5.1ComputingRelatedLegislationDataProtectionAct1999:

• Datamustbeprocessedfairlyandlawfully• Datamustbeadequate,relevantandnotexcessive• Datamustbeaccurateandkeptuptodate• Datamustnotbekeptforlongerthannecessary• Datamustonlybeusedforthepurposeforwhichitwascollected• Datamustbekeptsecure• Datamustbehandledinaccordancewithpeople’srights• DatamustnotbetransferredtocountriesoutsidetheEUwithoutadequate

protection• AlldatausersmustregisterwiththeInformationCommissioner

ComputerMisuseAct1990createdfournewoffences:

• Unauthorisedaccesstocomputersystems• Unauthorisedaccesswithintenttocommitoraidcrime• Unauthorisedmodificationofcomputersystems• Making,supplyingorobtaininganythingthatcanbeusedintheaboveoffences.

Copyright,DesignsandPatentsAct1988makesitillegalto:

• Copyworksofintellectualproperty(software,music)electronicallytoredistribute• Rentingworksofintellectualpropertywithoutthepermissionofthecopyright

holder• Puttingintellectualpropertyonasharednetworkwithoutthepermissionofthe

copyrightholderRegulationofInvestigatoryPowersAct2000allows:

• Certainpublicbodiestomonitorpeople’sInternetactivities• Certainpublicbodiestodemandpeoplehandoverencryptionkeys• CertainpublicbodiestodemandISPshandovercustomerinformationandtoinstall

surveillanceequipmentExamTechniqueYouarelikelytobeaskedquestionsonlawsin9markquestions.In9markquestions,thereare4marksforknowledge,2marksforapplicationand3forevaluation.So,ifaskedaboutpeoplestealingafilmfromaCGIcompany’scorporatenetwork,youshouldusethefollowingstructure:

o Knowledge:UnauthorisedaccesstocomputersystemsisillegalundertheComputerMisuseAct.

o Knowledge:Itisanadditionaloffencetogainunauthorisedaccesswiththeintentionofcommittingcrime.

o Application:Ifthepersonwhogotthefilms,hackedthecompany’scorporatenetworktodoso,thentheywillbeinbreachofthefirstoffence.

o Evaluation:Thisisrelevantonlyifthepersonwhoobtainedthemhadtogainunauthorisedaccess.Itisnotthesameifsomebodyworkingforthefirmleakedit.

1.5.2MoralandethicalissuesComputersintheworkforcehasledtomanylow-skillmanufacturingjobsandlow-skillservicejobsbeingautomated.FirmssuchasGoogleandAmazonareabletomakehugeamountsofmoney,whileemployingveryfewpeople.Automated decisionmaking iswhere computermake important, potentially life or deathdecisions.Forinstance,aself-drivingcarmaymakeadecisionthatkillssomebody,ormakesadecisionthatprioritisesthelifeofagroupofpeopleoveroneperson.Ineithercase,thereisaquestionofwhoisresponsibleforthedeaths.Theprogrammer?Themanufacturer?Artificial intelligencesystemscanbeused indifferentscenarios.For instance, theycanbeusedtodetectcreditcardfraud,orpredictcustomershoppingtoordergoodsinadvanceorattempttodiagnosepatientsbasedontheirsymptoms.Theenvironmentalconsiderationsofcomputersystemsincludethattechnologyhasledtoamassiveincreaseinelectronicwastebeingdiscardedinlandfills.Thisisespeciallytruesincephoneshaveaveryshortlifecycle.Examplesofusingcomputerstomonitorbehaviourincludemonitoringemployees’internetactivity,monitoringtheinternetactivityofthosesuspectedofcrimeandtaggingcriminals.Different governmentsattempt to censor information. It couldbe that this information isagainstthepolitical lineofthegovernment incountriessuchasChinaandNorthKorea. Itcouldbethecasethattheinformationispornographicorpiratedcontent.PiracysitessuchasPirateBayallowpeopletoaccessfilms,music,etc.forfree.However,thisalsomeansproducersofcontentsuchasfilmsandmusicdonotreceivepaymentfortheirwork.Ifdoneonawideenoughscale,thiscanmakeproducingthiscontentunprofitable.Theinternetalsoallowsforoffensivecommunicationse.g.‘trolling’andcyber-bullying.Thismaybe in the form of death threats ofmisogynistic slurs. It is difficult for platforms such asFacebooktodecidewhatshouldberemoved.Waystomakewebsitesaccessible:

o Makingthewebsitefriendlytoscreenreaderso Addingalternativetexttoimageso Takingintoaccountcolourblindnesswhendesigningcolourschemes

2.1 ComputationalThinking2.1.1ThinkingAbstractlyWhyisabstractionnecessary?

o Removethingsthatareunnecessary

o Theymayrequireadditionalprogrammingefforto Theymaydetractfromthepurposeoftheprogramo Savecomputationalresourcese.g.memory

2.1.2ThinkingAheadCachingCaching iswhere frequentlyperformed computationsordata thathas tobe requested isstored, to reduce time in the future. For instance, your web browser is likely to cachefrequentlybrowsedwebpages.Theadvantageisthatitreducestimeforaprogramtorun.Thedisadvantage is that it increases theamountof storageused.Youcan thinkof itasaspace-timetradeoff.ReusableComponentsThisiswhereaprogramismadefromanumberofsmallerindependentcomponents,thatcanbereused.Thisisdoneasreusablecomponentsmightbeusefulinthefuture.Thiswillsaveprogrammertime.

2.2 ProblemSolving2.2.1ProgrammingtechniquesSequence–Whereoneinstructionisexecuted,followedbyanother.Selection–Whereapieceofcodeisonlyexecutedifacertainconditionismet.Iteration–Whereapieceofcodeisexecutedrepeatedlyuntilacertainconditionismet,orforasetnumberoftimes.Variable–Anidentifierassociatedwithamemorylocationusedtostoredataandwhosecontentscanbechangedatruntime.GlobalVariable–Avariablethatcanbeaccessedfromanywhereinaprogram.LocalVariable–Avariablewhichcanonlybeaccessedfromtheconstructitwasdefinedin.Constant–Anidentifierassociatedwithavaluethatcannotbechangedduringaprogram’sexecution.Array–Astaticdatastructureconsistingofalistofvaluesstoredcontiguouslyinamemorylocationaccessiblefromasingleidentifierwithanindex.Procedure–Anamedsubsectionofaprogramthatperformsaspecifictaskbutdoesnotnecessarilyreturnafunction.Function–Anamedsubsectionofaprogramthatperformsaspecifictaskandreturnsvalue.

Passbyvalue–Thisiswhereacopyofthedatapassedtoafunctionispassedasaparameter.Passbyreference–Thisiswhereamemoryaddresstoapieceofdatatoafunctionispassedasaparameter.IDE–Asingleprogramusedtodevelopprogramsmadefromanumberofcomponentse.g.aneditor,acompiler,adebugger,etc.

2.3 Algorithms2.3.1AlgorithmsBigONotation

!(1) ConstantTime!(lg ') LogarithmicTime!(') Lineartime!('() Polynomialtime,where)isaconstant.

!()*)usually!(2*) Exponentialtime,where)isaconstant.Whenwesayanalgorithmtake!(, ' ),whatwearestrictlysayingisthatanalgorithm’smaximumrunningtime(thatitcouldpossibletake)as',whichistheinputsizee.g.thelengthofanarray,variesisproportionalto, ' .BigONotationprovidesanupperbound.IntractableProblemAproblemisintractableisifitcanbesolvedintheory,butinpracticeitcannotbesolved.Normally,computerscientistssayingthataproblemisintractableifittakesanexponentialtime,asafunctionofitsinput.Thismayseemlikeaveryroughdefinition,butitmakesalotofsense.Imagineaproblemtakes!(2*),andyouwantedtosolveit.Supposewithyourcurrentcomputeryoucouldsolveforwhen' = 5,foryoutobeabletosolve' = 6inthesametime,yourcomputerwillhavetotwiceasfast.Tosolve' = 7,itwillhavetobefourtimesasfast.Evenifcomputersdoubledinspeedeveryyear,ina100yearstimeyouwouldonlybeabletosolve' = 105.SortingAlgorithmsBubbleSortprocedurebubbleSort(input)fori=0to(input.length–2)forj=0to(input.length–2–i)ifinput[j]>input[j+1]then//Swapinput[j]andinput[j+1]a=input[j+1]input[j+1]=input[j]

input[j]=aendifnextjnextiendprocedureInsertionSortprocedureinsertionSort(input)fori=1to(input.length–1)key=input[i]whilei>0&&input[i–1]>keyinput[i]=input[i–1]i=i-1endwhileinput[i]=keynextiendprocedureThemergesortalgorithmbelowcanactuallybesimplifiedwithcleverBooleanalgebrabutitissimplertounderstandlikethis.MergeSort//Thismethodsmergesthetwosublistsinput[start..midpoint]//andinput[midpoint+1..end]proceduremerge(input,start,midpoint,end)arrayworkingMemory[end–start+1]positionA=start//ThisisthepositionintothefirstlistpositionB=midpoint+1//Thisisthepositionintothesecondlistfori=0to(end–start+1):ifpositionA>midpointthenworkingMemory[i]=input[positionB]positionB=positionB+1elseifpositionB>endthenworkingMemory[i]=input[positionA]positionA=positionA+1elseifinput[positionA]<input[positionB]thenworkingMemory[i]=input[positionA]positionA=positionA+1elseworkingMemory[i]=input[positionB]positionB=positionB+1endifendifnextifori=0to(end–start+1):input[i]=workingMemory[i]

nextiendprocedureproceduremergesort(input,start,end)ifstart<endthen//IntegerDivisionmidpoint=(start+end)/2mergeSort(input,start,midpoint)mergeSort(input,midpoint+1,end)merge(input,start,midpoint,end)endifendprocedureQuickSort//Thisalgorithmssplitsthelistintotwosublists.//Onewhichissmallerthanthepivot//Anotherthatislargerthanthepivot//Thealgorithmreturnsthepositionofthepivotfunctionpartition(input,start,end)k=start–1//Thepivotisalwaystakentobetheitemattheendpivot=input[end]//Thealgorithmworksbysplittingtheinput,intothreesublists//Firstthesectionofthelistthatissmallerthanthepivot//Thisisinput[start..k]//Sincekinitiallyequalsstart–1,thissectionisempty//Thenyouhaveinput[k+1..i]//Thisisthesectionwhichisgreaterthanthepivot//Thenyouhaveinput[i..end]whichisthesublistyettobeprocessed//Eventuallyinput[i..end]willbeempty,sotherewillonlybetwosublists.fori=starttoend–1ifinput[i]<=pivotthenk=k+1//Swapinput[k]andinput[i]a=input[k]input[k]=input[i]input[i]=aendifnexti//Thelastitemtobesmallerthanorequaltothepivotisthepivot//So,kpointstothelocationofthepivotreturnkendfunctionprocedurequicksort(input,start,end)ifstart<endthenpivot=partition(input,start,end)

quicksort(input,start,pivot-1)quicksort(input,pivot+1,end)endifendprocedureBinarySearchfunctionbinarySearch(input,search)lower=0upper=input.lengthmiddle=(lower+upper)/2whilelower<=upperifinput[middle]=searchthenreturnmiddleelseifinput[middle]<searchthenupper=middle+1elselower=middle–1endifendwhilereturn-1endfunctionLinearSearchfunctionlinearSearch(input,search)fori=0toinput.lengthifinput[i]==searchthenreturniendifnextireturn-1endfunctionThisisjustonewayofdoingDijkstra’sAlgorithm.NoteIfindtheshortestdistancetoeverynode.Tomakeitmoreefficient,youcantakeanadditionalparameterwhichisthegoalnodeandstoponceyou’vefoundtheshortestdistancetothegoalnode.Dijkstra’sAlgorithm//Thisfunctionreturnsahashmapbetweennodesinthegraphandthe//shortestdistancefromthestartNode//Weareassumingthereisafunctiondist(a,b)whichgivesyouthedistancebetween//twoconnectednodes.functiondijkstra(startNode)map=createHashMap()notProcessed=createLinkedList()processed=createLinkedList()//mapisthenameofthehashmapwewillbecompilingduringthisalgorithm//andwewillreturn.

//notProcessedisthelistofnodesthatwehavenotfoundtheshortestdistanceto//butthatwehaveencountered//processedisthelistofnodesthatwehavefoundtheshortestdistanceto//Initially,mapwillonlystoretheshortestdistancewehaveseensofar//OncewearesureitistheshortestdistancewemoveanodefromnotProcessed//Toprocessed//Initiallywehaveonlyencounteredthestartnode.notProcessed.add(startNode)//Obviouslyyoudon’thavetouselinkedlists//Youcanusewhateverdatastructurefloatsyourboat//Butithastobeadynamicdatastructure//Wedonotstopuntilthereisnothinglefttoprocessedwhile!notProcessed.isEmpty()//FirstwefindthenodeinnotProcessedwiththeshortestdistancesofarminIndex=0minDistance=-1fori=0tonotProcessed.getLength()ifmap.get(notProcessed.get(i))<minDistanceminIndex=iendifendfor//ThatnodeisremovedfromnotProcessednode=notProcessed.get(i)notProcessed.remove(node)//Andaddedtoprocessedprocessed.add(node)//ThenweadditsneighbourstonotProcessed//Unlessthey’realreadyinnotProcessedorprocessedneighborus=node.getNeighbours()fori=0toneighbours.getLength()x=neighbours.get(i)if!(processed.contains(x))thenifnotProcessed.contains(x)then//Ifwearehereitmeansthatwehavefoundanotherpathtoanode//Thatwehavealreadyseen//thismightbetheshorterpaththanalreadyhasbeenfoundifmap.get(x)>map.get(node)+dist(node,x)then//Updatethedistancemap.put(x,map.get(node)+dist(node,x))endif

else//ThismeansitisnotinnotProcessed//SoweadditnotProcessed.add(x)map.set(x,map.get(node)+dist(node,x))endifendifendforreturnmapendfunctionDijkstra’salgorithmwillalwaysfindtheshortestdistancefromanodetoagoalnode.However,indoingsoitcheckseverypath.TheA*pathfindingalgorithmfindsapathfromonenodetoagoalnode,butguessesi.e.usesaheuristictochoosewheretosearch.Forinstance,theheuristicmightbetheshortestdistancebetweenthecurrentnodeandthegoalnode(e.g.usingPythagoras’theorem).Inthisalgorithm,Iassumethereisaheuristicalgorithmguess(current,goal)whichestimatesthedistancesbetweencurrentandgoal.However,theA*algorithmwillalwaysfindapathifoneexists.Myimplementationofthealgorithmdoesnotreconstructthepath,butthatcanbeaddedwithafewmodifications.A*PathfindingAlgorithm//Thisfunctionsreturns0ifithasfoundapath//Otherwiseitreturns0functionA*(startNode,goalNode)map=createHashMap()notProcessed=createLinkedList()processed=createLinkedList()//mapisthenameofthehashmapwewillbecompilingduringthisalgorithm//andwewillreturn.//notProcessedisthelistofnodesthatwehavenotprocessed//butthatwehaveencountered //processedisthelistofnodesthatwehaveprocessed//mapwillstoretheshortestdistancetoanodethatwehaveseensofar//Initiallywehaveonlyencounteredthestartnode.notProcessed.add(startNode)while!notProcessed.isEmpty()//Hereiswheretheguessingbegins//Wechooseanodebasedontheshortestdistancewehaveseensofartoit//AndanestimationofhowlongitwilltaketogettothegoalnodeminIndex=0minDistance=-1fori=0tonotProcessed.getLength()

ifmap.get(notProcessed.get(i))+guess(notProcessed.get(i),goalNode)<minDistanceminIndex=iendifendfor//ThatnodeisremovedfromnotProcessednode=notProcessed.get(i)notProcessed.remove(node)//Andaddedtoprocessedprocessed.add(node)//ThenweadditsneighbourstonotProcessed//Unlessthey’realreadyinnotProcessedorprocessedneighborus=node.getNeighbours()fori=0toneighbours.getLength()x=neighbours.get(i)//Firstwecheckiftheneighbouristhegoalnodeifx==goalNodethen//Wedidit!return0endifif!(processed.contains(x))thenifnotProcessed.contains(x)then//Ifwearehereitmeansthatwehavefoundanotherpathtoanode//Thatwehavealreadyseen//thismightbetheshorterpaththanalreadyhasbeenfoundifmap.get(x)>map.get(node)+dist(node,x)then//Updatethedistancemap.put(x,map.get(node)+dist(node,x))endifelse//ThismeansitisnotinnotProcessed//SoweadditnotProcessed.add(x)map.set(x,map.get(node)+dist(node,x))endifendifendfor//Ifwegettohereouralgorithmhasfailedtofindapath//Whichmeansapathdoesn’texistreturn-1endfunction

Recommended