chapter one: introduction › classes › 2016_09_cs010 › lectures › lec… · the cpu (aka...

26
Chapter One: Introduction A SHORT INTRODUCTION TO HARDWARE, SOFTWARE, AND ALGORITHM DEVELOPMENT

Upload: others

Post on 02-Feb-2021

0 views

Category:

Documents


0 download

TRANSCRIPT

  • Chapter One: Introduction A SHORT INTRODUCTION TO HARDWARE, SOFTWARE, AND ALGORITHM DEVELOPMENT

  • Chapter Goals •  Inthischapteryouwillearn:

    •  Aboutcomputerhardware,so8wareandprogramming•  HowtowriteandexecuteyourfirstPythonprogram•  Howtodiagnoseandfixprogrammingerrors•  Howtousepseudocodetodescribeanalgorithm

    9/2/16 2

  • Our First Definition Algorithm:

    •  AnalgorithmisastepbystepdescripConofhowtosolveaproblem.

    9/2/16 3By http://www.lib.k-state.edu/ - http://www.lib.k-state.edu/depts/spec/rarebooks/cookery/apicius1541.html, Public Domain, https://commons.wikimedia.org/w/index.php?curid=5530026

    The large collection of recipes De re coquinaria, conventionally entitled 'Apicius', appeared in the 4th or 5th century and is the only more or less complete surviving cookbook from the classical world. It lists the courses served in a meal as 'Gustatio' (appetizer),'Primae Mensae' (main course)'Secundae Mensae' (dessert).

  • Computer Programs •  Acomputerprogramtellsacomputerthesequenceofstepsneededtocompleteaspecifictask•  TheprogramconsistsofaverylargenumberofprimiCve(simple)instrucCons

    •  Computerscancarryoutawiderangeoftasksbecausetheycanexecutedifferentprograms•  Eachprogramisdesignedtodirectthecomputertoworkonaspecifictask

    Programming:

    •  Theactofdesigning,implemenCng,andtesCngcomputerprograms

    9/2/16 4

  • Hardware and Software THE BUILDING BLOCKS THAT MAKE UP A COMPUTER

    9/2/16 5

  • Hardware •  Hardwareconsistsofthephysicalelementsinacomputersystem.

    •  Someveryvisibleexamplesarethemonitor,themouse,externalstorage,andthekeyboard.

    •  Thecentralprocessingunit(CPU)performsprogramcontrolanddataprocessing

    •  Storagedevicesincludememory(RAM)andsecondarystorage•  Harddisk•  Flashdrives•  CD/DVDdrives

    •  Input/outputdevicesallowtheusertointeractwiththecomputer•  Mouse,keyboard,printer,screen…

    9/2/16 6

  • Simple View of a Computer’s Components

    9/2/16 7

  • The CPU (aka “a core”) •  TheCPUhastwocomponents,thecontrolunitandthearithme.clogicunit

    •  ThecontrolunitdirectsoperaConoftheprocessor.•  Allcomputerresourcesaremanagedbythecontrolunit.•  ItcontrolscommunicaConandco-ordinaConbetweeninput/outputdevices.•  ItreadsandinterpretsinstrucConsanddeterminesthesequenceforprocessingthedata.

    •  ItprovidesCmingandcontrolsignals

    •  Thearithme7clogicunitcontainsthecircuitrytoperformcalculaConsanddocomparisons.•  ItistheworkhorseporConofthecomputeranditsjobistodopreciselywhatthecontrolunittellsittodo.

    9/2/16 8

  • The CPU

    9/2/16 9

  • Storage •  Therearetwotypesofstorage:

    •  PrimaryStorage•  SecondaryStorage

    •  Primarystorageiscomposedofmemorychips:electroniccircuitsthatcanstoredataaslongasitisprovidedelectricpower

    •  Secondarystorageprovidesaslower,lessexpensivestoragethatispersistent:thedatapersistswithoutelectricpower

    •  Computersstorebothdataandprograms•  Thedataandprogramarelocatedinsecondarystorageandloadedintomemorywhentheprogramisexecuted

    9/2/16 10

  • Memory •  Asimplewaytoenvisionprimarymemoryisatableofcellsallthesamesize,onebyte,andeachcontainingauniqueaddressbeginningwith0.•  The“typical”computerhasamainmemoryrangingfrom4gigabytes(GB),to32GB.

    •  Howbigisagigabyte?•  Abyteis8bits.•  Akilobyte,KB,is1024bytes,or“about1thousandbytes.”•  Amegabyte,MB,is1,048,576bytes,or“about1millionbytes.”•  Agigabyte,GB,is1,073,741,824bytesor“about1billionbytes.”

    9/2/16 11

  • Executing a Program •  PrograminstrucConsanddata(suchastext,numbers,audio,orvideo)arestoredindigitalformat

    •  Whenaprogramisstarted,itisbroughtintomemory,wheretheCPUcanreadit.

    •  TheCPUrunstheprogramoneinstrucConataCme.•  Theprogrammayreacttouserinput.

    •  TheinstrucConsanduserinputguidetheprogramexecuCon•  TheCPUreadsdata(includinguserinput),modifiesit,andwritesitbacktomemory,thescreen,orsecondarystorage.

    9/2/16 12

  • Software •  So1wareistypicallyrealizedasanapplicaConprogram

    •  Microso8Wordisanexampleofso8ware•  ComputerGamesareso8ware•  OperaCngsystemsanddevicedriversarealsoso8ware

    •  So8ware•  So8wareisasequenceofinstrucConsanddecisionsimplementedinsomelanguageandtranslatedtoaformthatcanbeexecutedorrunonthecomputer.

    •  ComputersexecuteverybasicinstrucConsinrapidsuccession•  ThebasicinstrucConscanbegroupedtogethertoperformcomplextasks

    •  ProgrammingistheactofdesigningandimplemenCngcomputerprograms

    9/2/16 13

  • Algorithms

    9/2/16 14

  • Introduction to Algorithms •  Ifyouwantacomputertoperformatask,youstartbywriCnganalgorithm

    •  AnAlgorithmis:•  asequence(theordermahering)ofacConstotaketoaccomplishthegiventask

    •  Analgorithmislikearecipe;itisasetofinstrucConswriheninasequencethatachievesagoal

    •  Forcomplexproblemsso8waredeveloperswriteanalgorithmbeforetheyahempttowriteacomputerprogram

    •  ForthisclassourgoalistoALWAYSwriteanalgorithmforeachproject

    •  Developingalgorithmsisafundamentalproblemsolvingskill•  IthasusesinmanyfieldsoutsideofComputerScience

    9/2/16 15

  • Algorithm: Formal Definition Analgorithmdescribesasequenceofstepsthatis:

    1.  Unambiguousa.  No“assumpCons”arerequiredtoexecutethealgorithmb.  ThealgorithmusespreciseinstrucCons

    2.  Executablea.  ThealgorithmcanbecarriedoutinpracCce

    3.  TerminaCnga.  Thealgorithmwilleventuallycometoanend,orhalt

    9/2/16 16

  • Problem Solving: Algorithm Design •  Algorithmsaresimplyplans

    •  Detailedplansthatdescribethestepstosolveaspecificproblem

    •  Youalreadyknowquiteafew•  Calculatetheareaofacircle•  Findthelengthofthehypotenuseofatriangle

    •  Someproblemsaremorecomplexandrequiremoresteps•  CalculatePIto100decimalplaces•  Calculatethetrajectoryofamissile

    9/2/16 17

  • A Simple Example

    9/2/16

    •  Asimplealgorithmtogetyourselfadrinkoforangejuice•  Forsimplicity,thefollowingaretrue:

    •  Youhaveacleanglassinthecabinet•  Youhaveorangejuiceinyourrefrigerator

    •  Soonevalidalgorithmis:1.  getaglassfromyourcabinet2.  gototherefrigeratorandgettheorangejuicecontainer3.  opentheorangejuicecontainer4.  pourtheorangejuicefromthecontainerintotheglass5.  puttheorangejuicecontainerbackintherefrigerator6.  drinkyourjuice

    18

  • Second Example: Selecting a Car Problem Statement:

    •  You have the choice of buying two cars.

    •  One is more fuel efficient than the other, but also more expensive.

    •  You know the price and fuel efficiency (in miles per gallon, mpg) of both cars.

    •  You plan to keep the car for ten years.

    •  Which car is the better deal?

    9/2/16 19

  • Developing the Algorithm Determinetheinputsandoutputs

    Fromtheproblemstatementweknow:•  Car1:Purchaseprice,FuelEfficiency•  Car2:Purchaseprice,FuelEfficiency•  Pricepergallon=$4.00•  Annualmilesdriven=15,000•  LengthofCme=10years

    Foreachcarweneedtocalculate:•  Annualfuelconsumedforeachcar•  Annualfuelcostforeachcar•  OperaCngcostforeachcar•  TotalcostofeachCar

    •  Thenweselectthecarwiththelowesttotalcost

    9/2/16 20

  • Translating the Algorithm to pseudocode

    •  Breakdowntheproblemintosmallertasks•  ‘Calculatetotalcost’foreachcar•  TocalculatethetotalcostforeachyearweneedtocalculatetheoperaCngcost•  TheoperaCngcostdependsontheannualfuelcost•  Theannualfuelcostisthepricepergallon*theannualfuelconsumed•  Theannualfuelconsumedistheannualmilesdrive/fuelefficiency

    •  Describeeachsubtaskaspseudocode•  totalcost=purchaseprice+operaCngcost

    9/2/16 21

  • The Psuedocode ForeachCar,computethetotalcostAnnualfuelconsumed=annualmilesdriven/fuelefficiency

    Annualfuelcost=pricepergallon*annualfuelconsumedOperaCngcost=LengthofCme*annualfuelcostTotalcost=purchaseprice+operaCngcost

    Iftotalcost1<totalcost2ChoseCar1

    ElseChooseCar2

    9/2/16 22

  • Bank Account Example •  ProblemStatement:

    •  Youput$10,000intoabankaccountthatearns5percentinterestperyear.Howmanyyearsdoesittakefortheaccountbalancetobedoubletheoriginal?

    •  Howwouldyousolveit?•  Manualmethod

    •  Makeatable•  AddlinesunCldone

    •  Useaspreadsheet!•  Writeaformula

    •  Perline,basedonlineabove

    9/2/16 23

  • Develop the algorithm steps •  Youput$10,000intoabankaccountthatearns5percentinterestperyear.Howmanyyearsdoesittakefortheaccountbalancetobedoubletheoriginal?

    •  Breakitintosteps•  Startwithayearvalueof0andabalanceof$10,000•  Repeatthefollowingwhilethebalanceislessthan$20,000

    •  Add1totheyearvalue•  MulCplythebalanceby1.05

    •  (5%increase)

    •  Reportthefinalyearvalueastheanswer

    9/2/16 24

  • Translate to pseudocode •  Pseudocode

    •  Half-waybetweennaturallanguageandaprogramminglanguage

    •  ModifiedSteps•  Settheyearvalueof0•  Setthebalanceto$10,000•  Whilethebalanceislessthan$20,000

    •  Add1totheyearvalue•  MulCplythebalanceby1.05

    •  Reportthefinalyearvalueastheanswer

    •  ThepseudocodeiseasilytranslatedintoPython

    9/2/16 25

  • The Python Language •  Intheearly1990’s,GuidovanRossumdesignedwhatwouldbecomethePythonprogramminglanguage

    •  VanRossumwasdissaCsfiedwiththelanguagesavailable•  TheywereopCmizedtowritelargeprogramsthatexecutedquickly

    •  Heneededalanguagethatcouldnotonlybeusedtocreateprogramsquicklybutalsomakethemeasytomodify•  ItwasdesignedtohaveamuchsimplerandcleanersyntaxthanotherpopularlanguagessuchasJava,CandC++(makingiteasiertolearn)

    •  Pythonisinterpreted,makingiteasiertodevelopandtestshortprograms

    •  PythonprogramsareexecutedbythePythoninterpreter•  Theinterpreterreadsyourprogramandexecutesit

    9/2/16 26