programming matlab and c++

440
 Introduction to Computers and Programming using C++ and MATLAB Alex F. Bielajew The University of Michigan Department of Nuclear Engineering and Radiological Sciences 2927 Cooley Building (North Campus) 2355 Bonisteel Boulevard Ann Arbor, Michigan 48109-2104 U. S. A. Tel: 734 764 6364 Fax: 734 763 4540 email:  [email protected] c  2000, 2001, 2002 Alex F Bielajew Revision: July 17, 2002

Upload: pulkit-gupta

Post on 09-Jul-2015

789 views

Category:

Documents


0 download

TRANSCRIPT

Introduction to Computers and ProgrammingusingC++ and MATLABAlexF.BielajewTheUniversity ofMichiganDepartment ofNuclear Engineering andRadiological Sciences2927 Cooley Building(North Campus)2355 Bonisteel BoulevardAnnArbor, Michigan48109-2104U.S.A.Tel: 734764 6364Fax: 734763 4540email: [email protected] _2000, 2001, 2002AlexFBielajewRevision: July17, 20022PrefaceThis bookarises out of acourseI teach, afour-credit (52hour) freshman-level courseIntroductiontoComputersandProgrammingbeingtaughtintheCollegeofEngineeringattheUniversityof Michigan. Thebookisinreasonablyroughshapeatthisstage. Itwasassembledfrommylecturenotestwoyearsago andisunderconstantrevision. Imaynevernishit! Awisepersononcesaid, Oldagehappens whenyoudwell moreonthepastthanonthefuture.Bythisdenition, Ihavefoundeternal youth, insofarasthisbookisconcerned.Myeducational objectivesarequitesimple. Thisisnotreallyacourseincomputing. Itisacourseinthinking,technicalthinking,logicalthinking,aboutformulatingaproblem,amathematical problem, a physics problem, a game, and then executing a solution and makingitwork. I considerthecomputerandtheabilityto programitasa kindof laboratoryalaboratorytoinvestigatepractically, thetheoriesandideasofothertechnical courses. Itispossible, forexample, toteachalotof Calculustostudentswithoutevermentioningtheword,andthereareseveralexamplesthroughoutthisbook.Thiscourseisnotaboutsyntax. Hence, thebookintroducestheminimumamountsyntaxtogetthroughaproblem. Indeed, Ievenkeepsomesyntaxhidden, toencouragestudentstodiscovertheirownalgorithms. So, if youarethinkingofusingthisbookasatechnicalreferenceinC++orMatlab,Ianticipatethatyouwillbedisappointed.The greatest value in this book, if there is any to be found, is in the exercises,problems andprojectsatthebackofalmosteverychapter. Theideal waytolearnacomputerlanguageistolearnalittlesyntaxandthentryit outonacomputer. Theideal waytothinkisnottoreadaboutit, but toactuallydoit! Thebookreects this. Thematerial inthechapters, separatedfromtheexercises, isworsethatuseless, forreadingthematerial andnotdoingtheproblemsisjustawasteoftime. Dotheproblems! Moreover, dontaskmeforthesolutions! Thereismuchmorepedagogical valueinawell-posedquestionthanawell-articulatedanswer.OK,Illstepomysoapboxnow!Severalprofessorsandmanystudentswho havecontributedto theideasputinto thisbook.Professor James HollowayandI have hadendless discussiononthe general problemofteaching algorithmic thinking to freshman. We still have not come to any conclusions exceptiiithat it is highly challenging and rewarding. As for how it actually gets done, well, to be sureit is a works-in-progress. I spent a very enjoyable term co-teaching this course (the rst timeI taught it) with Professor Ken Powell. Thanks, Ken, for nursing me through that rst year!BothJamessandKensdiversecomputationalbackgroundsarereectedtosomedegreeinthisbook.Ioweadebtofgratitudetothedozensof GraduateStudentInstructorswhohavetaughtwith me on this course. One of them, Dan Osborne, deserves special recognition. He is one ofthe most gifted and committed teachers I have ever encountered. Dan and I spent hour afterhour discussingthechallengesof teachingcomputingand thinkingskillsto undergraduates.To the1300 or soundergraduates,mostlyfreshmen,who havetakenmycourse: EverytimeIteachthiscourseIlearnsomethingnewaboutcomputing,about teaching,about thejoyofmakinganearlydeectioninastudentscareer.Thesupportof theDean for EngineeringUndergraduateEducation,ProfessorGary Herrin,Iacknowledgedwarmly. Garyremovesmanyoftheroadblocksthatcouldotherwisemakelarge-scaleteachingodious. ItisremarkabletohaveononessideanadministratorwhoismorelikelytosayYes!ratherthanNo!tomynumerousoutrageousrequests.Finally, none of this would be possible without the support of my wife, Karen Vineberg. Yourstrong support during the insanely busy term teaching this course is deeply appreciated. YesKaren, you are right, I dolove teaching this course despite the long hours, the insomnia, thelostweekendsandlostvacations.ToallofthemIgivemythanksandtoKaren,mylove. Youreortswillgotohelpfuturestudents.AFB,July17,2002Contents1 Introductiontothecourse 11.1 Whatthiscourseisabout . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11.2 Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62 Datarepresentations 72.1 Bits,nibbles,bytesandwords . . . . . . . . . . . . . . . . . . . . . . . . . . 72.2 4-bitBinary,HexadecimalandDecimalDigits . . . . . . . . . . . . . . . . . 92.3 Binaryarithmetic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92.4 Convertingfrombinarytodecimal . . . . . . . . . . . . . . . . . . . . . . . 102.4.1 Wholenumbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102.4.2 Realnumbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112.5 Binaryintegerarithmeticoncomputers. . . . . . . . . . . . . . . . . . . . . 112.5.1 Twoscomplementintegerarithmetic . . . . . . . . . . . . . . . . . . 122.6 32-bitBinary,Hexadecimal,UnsignedandSignedIntegers . . . . . . . . . . 132.7 Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153 AlgorithmsandPseudocodes 233.1 Whatisanalgorithm? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233.2 Flowchartrepresentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243.3 Pseudocoderepresentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243.4 Decisions,conditionals,branchinstructions . . . . . . . . . . . . . . . . . . 253.5 Loopingorjumpinstructions . . . . . . . . . . . . . . . . . . . . . . . . . . 25iiiiv CONTENTS3.6 Sequencing,branchingandlooping . . . . . . . . . . . . . . . . . . . . . . . 263.7 Amini-summarybeforetheexamples . . . . . . . . . . . . . . . . . . . . . . 273.8 Someexamples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273.8.1 The Breakfast algorithm, or, Bielajews Sunday Morning Internationally-famouspancakes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 283.8.2 Solveforx: Ax2+ Bx + C= 0whereA, B, Carearbitraryconstants 293.8.3 Iteration: Asummingloop. . . . . . . . . . . . . . . . . . . . . . . . 333.8.4 Iteration: Aproductloop . . . . . . . . . . . . . . . . . . . . . . . . 363.9 Anasideoncomputerarchitecture . . . . . . . . . . . . . . . . . . . . . . . 403.9.1 WhatdoesS= S + 1mean?. . . . . . . . . . . . . . . . . . . . . . . 403.10 Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 413.11 Projects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 474 GettingstartedinC++ 494.1 Simpleinput/output(I/O):ArstprograminC++ . . . . . . . . . . . . . . 494.2 Compiling,linking,loadingandrunning . . . . . . . . . . . . . . . . . . . . 524.3 Declaringandinitializingvariables . . . . . . . . . . . . . . . . . . . . . . . 554.4 IntegermathinC++. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 574.5 FloatingpointmathinC++. . . . . . . . . . . . . . . . . . . . . . . . . . . 594.6 Theif/else if/elseconstruct . . . . . . . . . . . . . . . . . . . . . . . . . 604.7 Logicalexpressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 634.7.1 LogicalexpressionswithANDorOR. . . . . . . . . . . . . . . . . . 664.7.2 Mixedarithmeticandlogicalexpressions . . . . . . . . . . . . . . . . 674.8 Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 694.9 Projects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 735 Loops 835.1 Thewhileloop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 835.2 Thedo/whileloop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 865.3 Theforloop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89CONTENTS v5.4 Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 945.5 Projects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1116 EarlyAbstractionFunctions 1236.1 Motivationforfunctions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1236.2 User-denedfunctions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1296.3 Example: Aproblemtackledwithteamwork . . . . . . . . . . . . . . . . . . 1346.4 Callbyvalue,callbyreference,referenceparameters . . . . . . . . . . . . . 1386.4.1 Theaddressofavariable. . . . . . . . . . . . . . . . . . . . . . . . . 1386.4.2 Call-by-valuevs. call-by-reference . . . . . . . . . . . . . . . . . . . . 1406.5 Therulesofscope. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1456.6 Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1536.7 Projects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1607 MoreVariableTypes,DataAbstraction 1677.1 Representationofoating-pointnumbers . . . . . . . . . . . . . . . . . . . . 1677.1.1 Whenisonenotone?Floatingpointanomalies. . . . . . . . . . . . . 1747.2 char: thecharactervariable . . . . . . . . . . . . . . . . . . . . . . . . . . . 1757.2.1 Characterstrings;thestringclass . . . . . . . . . . . . . . . . . . . . 1777.3 Thevectorclass. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1797.3.1 Introductiontovectors . . . . . . . . . . . . . . . . . . . . . . . . . . 1797.3.2 Declaringandusingvectors . . . . . . . . . . . . . . . . . . . . . . . 1807.3.3 Vectorsyntaxandrules: . . . . . . . . . . . . . . . . . . . . . . . . . 1827.3.4 Vectorsandfunctions. . . . . . . . . . . . . . . . . . . . . . . . . . . 1877.4 Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1898 MoreDataAbstraction,Arrays,Structures 1998.1 Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1998.1.1 Declaringa2-dimensionalarray . . . . . . . . . . . . . . . . . . . . . 2008.1.2 Initializinga2-dimensionalarray . . . . . . . . . . . . . . . . . . . . 201vi CONTENTS8.1.3 Passingatwo-dimensionalarraytoafunction . . . . . . . . . . . . . 2048.2 Characterarrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2098.2.1 Onedimensionalcharacterarrays . . . . . . . . . . . . . . . . . . . . 2098.2.2 Twodimensionalcharacterarrays . . . . . . . . . . . . . . . . . . . . 2118.3 Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2118.3.1 Thestructuredenition . . . . . . . . . . . . . . . . . . . . . . . . . 2128.3.2 Wherecanstructuresbedened? . . . . . . . . . . . . . . . . . . . . 2138.3.3 Themembersofastructure . . . . . . . . . . . . . . . . . . . . . . . 2138.3.4 Declaringstructurevariables. . . . . . . . . . . . . . . . . . . . . . . 2138.3.5 Assigningvaluestostructuremembers . . . . . . . . . . . . . . . . . 2138.3.6 Re-assigningvaluesofstructuremembers. . . . . . . . . . . . . . . . 2148.3.7 Functioncall-by-valueofastructure . . . . . . . . . . . . . . . . . . 2148.3.8 Functioncall-by-referencetoastructure . . . . . . . . . . . . . . . . 2158.3.9 Structurearrays. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2158.3.10 Exampleusingstructuresandarrays: Iontransport . . . . . . . . . . 2188.4 Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2228.5 Projects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2289 MiscellaneousTopics 2399.1 Generatingrandomnumbers . . . . . . . . . . . . . . . . . . . . . . . . . . . 2399.1.1 Example: Integratingfunctionsbyrandomsampling . . . . . . . . . 2469.2 SimpleSorting: Thebubbleorsinkingsort . . . . . . . . . . . . . . . . . . . 2489.3 RecursionAfunctioncallingitself . . . . . . . . . . . . . . . . . . . . . . . 2499.4 InputandOutputusingles . . . . . . . . . . . . . . . . . . . . . . . . . . . 2529.4.1 FileandstreamhandlinginC++. . . . . . . . . . . . . . . . . . . . 2529.4.2 Creatingsequentialaccesslesandwritingtothem. . . . . . . . . . 2559.4.3 Readingfromsequentialaccessles . . . . . . . . . . . . . . . . . . . 2589.5 Commandlinearguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2619.6 Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 264CONTENTS vii10APotpourriofApplications 26710.1 Findingazerousingthebinarychop . . . . . . . . . . . . . . . . . . . . . 26711ProgramminginMATLAB 27111.1 AtasteofMATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27111.2 ArraysinMatlab . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27311.3 Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27911.3.1 Theforloop. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27911.3.2 Thewhileloop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28211.4 Theif/elseconstruct . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28211.5 SomeMatlabterminology . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28311.6 OperatorsinMATLAB. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28411.6.1 MathoperatorsinMatlab . . . . . . . . . . . . . . . . . . . . . . . . 28411.7 PointwiseoperatorsinMATLAB . . . . . . . . . . . . . . . . . . . . . . . . 28511.7.1 LogicalOperatorsinMatlab. . . . . . . . . . . . . . . . . . . . . . . 28611.8 M-les . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28811.8.1 ScriptM-les . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28811.8.2 FunctionM-les. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29211.9 Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29511.10Projects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32711.10.1Supplementarymaterial: Trajectorieswithoutairresistance . . . . . 34611.10.2Supplementarymaterial: Trajectorieswithairresistance . . . . . . . 34611.10.3Supplementarymaterial: Steppingalgorithms . . . . . . . . . . . . . 34711.10.4Supplementarymaterial: Trajectoriesofobjectsintheuniverse . . . 35411.10.5Supplementarymaterial: Steppingalgorithms . . . . . . . . . . . . . 35512Graphics 36712.1 TwoDimensionalPlots. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36712.1.1 Abasicplot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36712.1.2 Usingdierentlinecolors . . . . . . . . . . . . . . . . . . . . . . . . 367viii CONTENTS12.1.3 Makingtitles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37012.1.4 Axislabels. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37012.1.5 Dierentlinestyles . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37012.1.6 Pointplots,plottingwithpointsymbols . . . . . . . . . . . . . . . . 37212.1.7 Plottingmorethanonethingatonce . . . . . . . . . . . . . . . . . . 37712.1.8 Subplots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37812.2 Threedimensionalgraphics . . . . . . . . . . . . . . . . . . . . . . . . . . . 37912.2.1 Plot3plots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37912.2.2 Meshplots. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37912.2.3 Axislabelling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38112.2.4 meshcandmeshzplots . . . . . . . . . . . . . . . . . . . . . . . . . . 38212.2.5 Surfaceplotsusingsurf. . . . . . . . . . . . . . . . . . . . . . . . . . 38212.2.6 Surfaceplotsusingsurfc . . . . . . . . . . . . . . . . . . . . . . . . . 38312.2.7 Surfaceplotsusingsur . . . . . . . . . . . . . . . . . . . . . . . . . 38312.2.8 Contourplotsusingcontour . . . . . . . . . . . . . . . . . . . . . . . 38412.2.9 Contourplotsusingcontour3 . . . . . . . . . . . . . . . . . . . . . . 38412.2.10Contourplotsusingpcolor . . . . . . . . . . . . . . . . . . . . . . . . 38412.2.11Contourplotsusingcontourf. . . . . . . . . . . . . . . . . . . . . . . 38512.2.12Contourplotswithlabels . . . . . . . . . . . . . . . . . . . . . . . . . 38513Miscellaneoustopics 38713.1 Pitfallreview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38713.1.1 Reviewofforloops . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38713.1.2 Reviewoffunctions. . . . . . . . . . . . . . . . . . . . . . . . . . . . 39013.2 TheMATLABway . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39513.3 SelectedApplications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39513.3.1 Freefallwithairresistance . . . . . . . . . . . . . . . . . . . . . . . . 39513.3.2 Diusionofchargedionsinanelectriceld . . . . . . . . . . . . . . . 40013.3.3 CalculationofElectricelds . . . . . . . . . . . . . . . . . . . . . . . 402CONTENTS ix13.4 SummaryoftheCourse . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40414ProgrammingStyleGuideforC++ 40515SyntaxreferenceforbeginningC++ 41316SyntaxreferenceformoreadvancedC++ 41717SyntaxreferenceforMATLAB 421x CONTENTSChapter1IntroductiontothecourseComputersarestupid. Theyonlygiveanswers.Computersareblindlyfaithful. Theyonlydowhatyoutell themtodo.Computersaredumb. Theydonotdowhatyouwantthemtodo.1.1 WhatthiscourseisaboutThiscourseiscalledENG101: IntroductiontoComputersandProgramming.TheCollegeofEngineeringBulletindescribesitasfollows(emphasisismine)Introduction to the organization of digital computers, computing (i.e. programming) as a toolinengineering,andprogramminginC++andMATLABLetsdeneafewthingsrst...Whatisanengineer?Whatisengineering?The American Heritage Dictionarydenes engineering as The application of science to prac-tical ends, suchas the design, manufacture, andoperationof structures, machines, andsystems. Anengineerisdenedassomeonewhopracticesengineeringasaprofession.Our denitionis somewhat broader. Engineeringis abroadrangeof technical endeavorthatstartswiththebasicsciences(tryingtocharacterizeandunderstandthebasiclawsofnature), integratesandsystematizesthisknowledgeandandbuildsthingsbasedontheseprinciples, manufacturesthesethingsonalargescale,andmakesitavailableforsocietalbenet. If we broaden our denition of things to ideas, methods, algorithms (a prescriptionfor doing something, like a recipe in cooking), as well as physical devices,then that capturestheessenceofwhatengineeringistoday.12 CHAPTER1. INTRODUCTIONTOTHECOURSEIn our College of Engineering you will encounterfaculty and sta who might otherwisehavebeencalledMathematicians,Physicists, ChemistsandBiologists.Whatisacomputer?Again,weappealatrsttosomestandardreferencetexts.AmericanHeritageDictionary1. One(aperson)whocomputes.Someofthebestexamples:- RichardFeynmanscomputersteamsof people workingout calculationsduringtheManhattanProject-CalculationofballisticstablesforWWII-Calculationofsine/cosine/logarithmtables2. A device (a machine) that computes,especially a programmable electronic machinethat performs high-speed mathematical or logical operations or that assembles,stores,correlates,orotherwiseprocessesinformation.OxfordEnglishDictionary1. Onewhocomputes;a calculator,reckoner;spec. a personemployedtomakecalcu-lationsinanobservatory,insurveying,etc. (Earliestreference1646).2. Acalculating-machine; esp. anautomaticelectronicdeviceforperformingmathe-matical orlogical operations; freq. withdeningwordprexed, asanalogue, digital,electroniccomputer(seethesewords). (Earliestreference1897).McGraw-Hill EncyclopediaofScienceandTechnologyAdevicethatreceives, processes, andpresentsinformation. Thetwobasictypesofcomputersareanaloganddigital. Althoughgenerallynotregardedassuch, themostprevalentcomputeristhesimplemechanical analogcomputer, inwhichgears, levers,ratchets,andpawlsperformmathematicaloperationsforexample,thespeedometerand thewatt-hour meter(usedto measureaccumulatedelectricalusage). Thegeneralpublic has become much more aware of the digital computer with the rapid proliferationof the hand-heldcalculator andalargevarietyof intelligent devices, rangingfromtypewriterstowashingmachines.OurdenitionAdevicethat1. accepts some formof input (usually disorganized or of some highly specic nature),2. respondstothisinputinformationinapre-determined(programmed)way,3. produces some form of output (usually more organized or coherent than the input)Somecommonexamplesofcomputers1.1. WHATTHISCOURSEISABOUT 3Personal: Wristwatch, electroniccarkeys, phone, radio, GPSdevice, calculator, lap-top...Inthehome: Stove, refrigerator, freezer, microwaveoven, clocksandtimers, toaster,coeemachines,thermostats,washeranddryer,TVs,VCRs,audioequipment...Automotive: fuel delivery, air/fuel mixture, spark advance, brakes (ABS), traction con-trol, suspensionadjustment, climatecontrol, navigation, computer-controlleddriving(comingsoon)...Mechanicalanalogcomputers: Wind-upclocks,toys,mechanicalcalculators...Electrical analogcomputers: Integrators, dierentiators, dierential equationsolvers,Christmaslightashers(cheapones!)...Digital computers: Calculators, PDAs, Palmcomputers, laptops, desktops, mini-computers,mainframecomputers....Digitalcomputers?Digital computers are the simplest of all! Theyonlyunderstandtwothings, whichwelabel0sand1s,oronoro,butmoreprecisely, statesoflowandhighvoltages.Computersswitchbetweenthesetwostatesvery, VERYquickly. Modernrun-of-the-milldigitalcomputerscanthrowabout100billionswitchespersecond! Thatsenoughtowriteabout10millionpagesoftextinonesecond.Theinputisrarelyacollectionof0sand1s, 011110000110... Itcanbeintheformoftextthatisconvertedto0sand1sorvoltagethatisdigitizedwithananalog-to-digital converter. (Musicalrecording,forexample.)Theoutputissimilarlyrarelyacollectionof0sand1s. Itcanbe1Ddata(words,numbers), 2D data (functions, charts, pictures, music),3D data (video, surfaces, time-evolvingfunctions)...The processing or computing or programming part is what the bulk of the courseisconcernedwith. Theprogrammingrespondstotheinputinsomepre-determinedway. Insomedigitalcomputerstheprogrammingisxed,forexample,adigitalclockoradigitalthermometer. Inthemostinterestingcases,theprogramcanbechanged.Inthiscoursewewilllearntoprogramprogrammabledigitalcomputers.4 CHAPTER1. INTRODUCTIONTOTHECOURSEHowaredigitalcomputersprogrammed?You can either start o the computer with the 0s and 1s in the right place, or, you use a pro-gramminglanguage. Programminglanguagesprovidetheprescription, thepre-determinedstepsthatinstructthecomputerhowtorespondtothevariousinputitgets. Wewilllearntwolanguagesinthiscourse.C++is a very popular (one of the most popular and common) language, a general-purposelanguagethatcanbeusedforallaspectsofcomputing. Itisthebestlanguagetouseifonewantstoteachmanyofthebasicoperationsthatacomputercanperform.MATLABisalanguage thatissuitedfor scienticand engineeringapplications,designedfor gettinganswers quickly, withtheminimumof eort, withreasonableguaranteethat the answer is correct. It also provides graphical output with a minimum of eort.WhatthiscourseisREALLYabout?ThehiddenagendaThiscourseisallaboutputtingideasintoaction. Itisabouttakingunderstoodnotionsofhowthingsworkandbuildingsomething, developinganumerical solutionforsomespecicproblem. Thisiswhatengineeringisallabout. Thecoursewill trytoputyourknowledgeof mathematicsandphysicstopractical use. Someof theproblemswemaysolveinthiscourse...HowcanIprogramacomputertoplayasimplegame?Howfarcanagolfballyintoa50mile/hourwind?Howndtheshortestdistancebetweentwopointswhenthelandscapeisnotat?IfItake10,000stepsinrandomdirections, howfar,onaverage, willIbefromwhereIstarted?HowcanIdocalculusonacomputer(integrate, dierentiate, ndmaximaandmin-ima)?WhereshouldIplacearadiatorinmyroomsothatIamwarmanddonothavetopaytoomuchfortheheat?HowcanImakeavacuum?1.1. WHATTHISCOURSEISABOUT 5WhatthiscourseisNOTREALLYabout?TheuglystuItisnotaprimarilyacourseoncomputerlanguagesyntax. Itmayseemlikeitattimes,butitreallyisnt. Learningsyntaxisjustameantotheend.It is not really a course on operating systems,computer hardware, or the ne detail ofhowcomputerswork. Wewilldiscussthisbutonlyenoughtogetthejobdone.EducationalObjectivesEngineering101, IntroductiontoComputersandProgramming, isintendedtogiveyouanexposureto, andachancetopractice, algorithmicthinking. Itdoessobyaskingyoutoactually solve problems using algorithms. This may be dierent from other courses that youhavetaken,becausewedonot tellyouexactlyhowto solvetheassignedproblems. Rather,weprovideyouwithtools that will allowyoutosolvethemandsomeexamples of howproblemsaresolved. Butyoumustcreativelyassemblethesolutionyourself.Notethat neither C++nor MATLABlanguages per se arethekeys tothecourse. Weteach you these languages so that you will havea means to expressalgorithms for executiononacomputer, but agreat manyother computer languages couldhavebeenselectedtosupportourcentral purposeof gettingyoutothinkaboutsolvingproblemsthroughasetofproceduralsteps. BecauseprogramminglanguagessuchasC++andMATLABcontainmanyconstructsanddemandgreatattentiontodetail, itiseasytolosesightof thetrueintellectual center of thecourse. But keepingafocus onalgorithmicthinkingwill makewritingprogramslessdicultandlesstimeconsuming.TheeducationalobjectivesofEngineering101include:Tointroducestudentstoalgorithmicthinkingintheirapproachtoproblemsolving.ToteachstudentstoimplementalgorithmsinANSIC++.ToteachstudentstoimplementalgorithmsinMATLAB.Tohavestudentsapplytheirknowledgeofelementaryphysicsandcalculus.Toprovidestudents withafoundationonwhichtobasetheir later applications ofcomputersinengineering.Studentswho successfullycompleteEngineering 101 (receivea grade of C or better) should:Designalgorithmstoaccomplishclearlyspeciedtasks.6 CHAPTER1. INTRODUCTIONTOTHECOURSEDisplayknowledgeofANSIC+syntaxandsemanticsDisplayknowledgeofMATLABsyntaxandsemantics.SuccessfullyimplementclearlystatedalgorithmsinC++.SuccessfullyimplementclearlystatedalgorithmsinMATLAB.Bepreparedtoengageindiscipline-specicinstructionincomputing.1.2 Problems1. Inthebroaddenitionofcomputerinthischapter, howmanycomputerscanyound: Onyourself?Inyourroom?Inacar?Inyourhome?2. Atypical 3rdgraderisalotsmarterthananycomputer. Theycanread, dosimplemath,playamusical instrument, memorizepoetryandwritestories. Generally,withsucientmotivation, theywill alsodoastheyaretold. Howmanywayscouldyouinstructa3rdgradertodeterminethevalueofwithouttheaidof acomputerorcalculatingdevice?Chapter2Datarepresentations2.1 Bits,nibbles,bytesandwordsbit Thedigitalcomputerprocessinghardwareismadeupoftransistorseachofwhichcanexistinonlyoneoftwopossiblestates, astateofhighvoltageorlowvoltage.This state of high/low (or on/o) is representedabstractly as 1/0 (one/zero). A bitissomepieceofmicroscopic(usually!) hardwarethatcanexistineitherofthesetwostates as determined by a programmer or computer designer. In addition to the voltagestates in a transistor in a computers memory chips or processing chips, there are manyothersforms: magneticdomainsinaoppydisk, harddiskormagnetictape, pitsina CDor DVD, holesinpapertape orcomputercards. Nowadays,therearebillionsortrillionsof bitsof variousformsinatypical computer. Abitmaybesimple, butitisusuallysosmall, typicallywell belowamicrometeracross(1micrometer=106m)thatwecanconceiveofcrammingbillionsofthemintoarelativelysmall volumeof space. Somebits,particularlythoseintheprocessingchipsofacomputer,canalsobemadetochangestatesveryrapidly, well underonenanosecond. (1nanosecond=109s.) So,wecan doa lot of dierentthings withlotsof bitsina veryshortspan oftime.nibbleAnibbleisacollectionof 4bits. Anibblecanbeinoneof 24=16separatecombinationsofbits.byteAbyteisacollectionof 2nibbles, or8bits. Abytecanbeinoneof 28=256separatecombinations of bits. This is enoughto, for example, associatewitheachuniquepatternoneofthecharactersoftheEnglishalphabet(upperandlowercase)plusall thecommonspecial characterswemayuse, forexample, inwritingEnglishproseoratechnical document, e.g. !$&(),:; ?. And, therewouldlotsof roomleftovertomakeotherinterestingassociations.78 CHAPTER2. DATAREPRESENTATIONSwordAwordisacollectionofbytestypically4for232= 4, 294, 672, 296 possiblecom-binations. Wecandoalotwithallthedierentrepresentationsofwords. Wewillsee, laterinthelecture, howwholenumberscanbeassociatedwiththevariouswordpatterns.Thenotionthat manybits canconspire, inverylargenumbers, toproducewonderfullyintricateobjectsisillustratedinthefollowing picturesof mydog, MatildaSkipBielajewII.(Yes,thatisherrealname!) Therstpicturewasgeneratedfromalethatwasabout12Megabytes, containing 96 million bits. It looks like real life. Yet, even when we zoom a little,westarttoseetheeectsoftheunderlyingbitstructure. Lookathowherwhiskersappearjagged. Underextrememagnication(oneofherwhiskers,again)weseethatthepictureismadeupofat,uniformlycoloredtiles. Eachoneofthesetilesisrepresentedby24bits,8bitseachforred,greenandblueintensity,that,toallappearances,aordsanapparentlyuniformtransitionofcolorfromtiletotile.2.2. 4-BITBINARY,HEXADECIMALANDDECIMALDIGITS 92.2 4-bitBinary,HexadecimalandDecimalDigits4-bitsofdata(anibble)canrepresentorberepresentedbyseveral dierentthings. Itiscommonforcomputerprogrammerstousehexadecimalnotation(0,1,2...9,A,B...F)asashorthandfor(0000,0001, 0010...1001,1010, 1011...1111). Seethefollowingtable.However, collection of a certain number of bits has to be given an interpretationone thatissensibletohumans. Onesuchassignment(whichiscompletelyarbitraryandisdecidedupon by the computer programmer or designer) is to assign decimal numbers to the stringsofbits. Suchanassignmentcouldlooklike:Binary Hexadecimal Decimalrepresentation representation assignment0000 0 00001 1 10010 2 20011 3 30100 4 40101 5 50110 6 60111 7 71000 8 81001 9 91010 A 101011 B 111100 C 121101 D 131110 E 141111 F 15Wewill usethisparticularrepresentationindoingsomesimplearithmeticintheexercisesandtheassignments.2.3 BinaryarithmeticLet us pretend that we have to do some arithmetic (additions and multiplications) using onlybinarynumbers. Thenumbers2,3,....9donotexist! Only0and1exist. Wealsoassumethattheoperationsofadditionandmultiplicationarecommutative(i.e. independentoftheorderofthemathematicaloperation).Theadditionofctionalbinarynumbersbase-2arithmeticlookslike:10 CHAPTER2. DATAREPRESENTATIONS0 + ? = ? + 0 = ?1 + 1 = 1010 + 1 = 1 + 10 = 1111 + 1 = 1 + 11 = 10010 + 10 = 10 + 10 = 100..1111 + 111 = 111 + 1111 = 10110...Themultiplicationofctionalbinarynumbersbase-2arithmeticlookslike:0? = ?0 = 01? = ?1 = ?1010 = 1010 = 1001011 = 1110 = 1101111 = 1001...1111111 = 1111111 = 1101001...Thearithmeticprocedureistheanalogoustothemorefamiliarbase-10system(thatarosesimplybecauseof our anatomy10 ngers). Additionsof columnsof numbers,subtraction,multiplication, the procedure of long division, can be accomplished by analogous procedures.Thereisnolimitto howlongactionalbase-2numbercanbeandwemayhavetocarryalongsomeextrainformationwitheachnumberitssign.2.4 Convertingfrombinarytodecimal2.4.1 WholenumbersHumansare usuallyquiteawfulat doing binaryarithmetic. If youare doing sucha calcula-tion,youcancheckbyconvertingthebinarynumbersintotheirdecimalequivalents.Ingeneral,to converta wholebinarynumberto a wholedecimalnumber,considera binarynumberoftheform:bnbn1bn2 b2b1b0,2.5. BINARYINTEGERARITHMETICONCOMPUTERS 11wherethebis areeither0 or 1. Wecomputea decimalnumberusingthe followingformula:d10= bn2n+ bn12n1+ bn22n2 b222+ b121+ b020.For example, the result of the two more dicult calculations above can be checked as follows:101102 = 1 24+ 0 23+ 1 22+ 1 21+ 0 20= 24+ 22+ 21= 1610 + 410 + 210= 2210istheresultofoneoftheadditions[11112(1510) + 1112(710)]above,while11010012 = 26+ 25+ 23+ 20= 6410 + 3210 + 810 + 110= 10510istheresult of oneof themultiplications [11112(1510)1112(710)] above. Notethat thesubscript 2indicates abinaryor base-2 number while the subscript 10indicates adecimalnumber.2.4.2 RealnumbersToconvertareal(non-whole)binarynumbertoareal decimal number, considerabinarynumberoftheform:bnbn1bn2 b2b1b0.b1b2 b(m2)b(m1)bm,where the bis are either 0 or 1 and a period, . separates the whole part, bi where i 0 fromthefractionalpart,biwherei< 0. Wecomputearealdecimalnumberusingthefollowingformula:r10= bn2n+bn12n1 b121+b020+b121+b222+b(m1)2(m1)+b(m)2m.It is not a whole lot dierent from the decimal numbers you are used to. However, sometimestheformulaecanlookalittlemessy.2.5 BinaryintegerarithmeticoncomputersComputers, because of their comprehension of data in binary terms naturally do their arith-meticusingthebase2representation. Thecircuitrywithinacomputerismosteasilysetupthisway. However, whenitcomestobase-2arithmeticandcomputers, thereisasub-tledierence! Forpractical reasons, computersmustdeal withintegersthatareniteinlength. 16bits, representing65,536separatepossibilitiesusedtobethenorm. Today, 32bitsiscommon(4294967296 possibilities)today. Soon,64bits(about181018)willbethestandard. Somecomputersnowadayspermithardware64-bitintegerarithmetic.Let us consider32-bit computers onlythe most common type of hardware available today.Inthecourseof doinganarithmeticcalculation, anybitsthat areset beyondthe32-bitboundaryarelosttheyfallintothebitbucketanddisappear.12 CHAPTER2. DATAREPRESENTATIONS2.5.1 TwoscomplementintegerarithmeticAstringof32-bitscanrepresentmanythingsbutwewill focusonhexadecimal, unsignedandsignedintegers. Thesesignedintegersmustalsocarryinformationastothesignofthenumber. Historically,therehavebeenseveralwaysto do this. Theindustryhas settledon 2s complement arithmetic because it simplies the process of adding positive, negativeormixednumbers. Inthisscheme, tonegateasignedinteger, onetakesthecomplement(changeallthe1sto0sandallthe0sto1s)ofthebinaryrepresentationandadds1toit. Thisisseeninthetableattheendofthischapter.Letsgivethenotationitothecomplementoftheintegeri. So,foranyi,i + i=11111111111111111111111111111111. Thatis:any32-bit pattern+ complementoftheabove= 11111111111111111111111111111111and11111111111111111111111111111111+ 00000000000000000000000000000001= 00000000000000000000000000000000sincethe33rdbit cannot beset! In2s complement arithmetictheexpressioni j iscalculated as i +j +1. So you see, computers can not really add and subtract, they can onlyadd(andtakecomplements)!Afewexampleshelpillustratethesimplicityofthetwos-complementscheme. Considera4-bitrepresentationofthenumber310=00112and410=01002. Therearetwotricksyoushould apply here: a) every time you see a negative sign in front of a bit pattern, i, to be usedinacalculation,convertittoapositivesign,changeitoi + 1anddothebinaryaddition,and, b)ifanalresulthasaleadingorder(leftmost)bitsetto1, itisanegativenumber,so,extracttheminussignandconverttheresultantbitpattern jtoj + 1.310 + 410= 00112 + 01002 = 01112 = 710310410= 0011201002 = 00112 + 11002= 11112 = 00012= 110310410= 0011201002 = 11012 + 11002 = 10012 = 01112= 710Seehoweasilyit all workedout! This is whythetwo-s-complement approachhas beenadopted. In order to handle negative integers one can convert them to their two-complementcounterpartsand add. Otherwise,specialcircuitrywouldhaveto bedevelopedfor handlingnegativenumbersandthatwouldbelessecient.2.6. 32-BITBINARY,HEXADECIMAL,UNSIGNEDANDSIGNEDINTEGERS 132.6 32-bitBinary, Hexadecimal, UnsignedandSignedIntegers32-bit computers can represent 232= 4, 294, 672, 296 dierent things but ONLY 4, 294, 672, 296dierentthings. Nowweconsidertheconventionalassignmentsto unsignedand signedintegers. Thereisalsothehexadecimal representationthatisassociatedwithevery4-bitsequence,asindicatedinthetablebelow.Theunsignedintegersassociatethedecimalnumber0toastringof320bits. Therestareformedbytheadditionby1ineitherbinaryordecimal. Themaximumunsignedintegers,therefore, is4, 294, 672, 295. Addingaonetothiscausesallthe32bitstogobacktozero,exactlyasifyouhadcycledtheodometerinyourcar! Itsthesameprinciple. Thereisno33rdbit,soyoucanimagineitjustfallsotheend.The signedintegers have the same sequence as the unsignedintegers upto 2311 =2147483647whichis thebit pattern01111111111111111111111111111111. Addingaonetothisgivesabitpatternof 10000000000000000000000000000000whichisinterpretedas231= 2147483648. Note that these two are complements of each other and that they addupto11111111111111111111111111111111, whichhas theinterpretation-1, consistentwiththe2scomplementschemedescribedabove.14 CHAPTER2. DATAREPRESENTATIONSBinary Hexadecimal UnsignedInt SignedInt00000000000000000000000000000000 00000000 0 000000000000000000000000000000001 00000001 1 100000000000000000000000000000010 00000002 2 200000000000000000000000000000011 00000003 3 300000000000000000000000000000100 00000004 4 4. . . .. . . .. . . .00000000000000000000000000001111 0000000F 15 1500000000000000000000000000010000 00000010 16 1600000000000000000000000000010001 00000011 17 17. . . .. . . .. . . .01111111111111111111111111111110 7FFFFFFE 2147483646 214748364601111111111111111111111111111111 7FFFFFFF 2147483647 214748364710000000000000000000000000000000 80000000 2147483648 -214748364810000000000000000000000000000001 80000001 2147483649 -2147483647. . . .. . . .. . . .11111111111111111111111111111100 FFFFFFFC 4294967292 -411111111111111111111111111111101 FFFFFFFD 4294967293 -311111111111111111111111111111110 FFFFFFFE 4294967294 -211111111111111111111111111111111 FFFFFFFF 4294967295 -12.7. PROBLEMS 152.7 Problems1. octal+octal=octalNote: Anoctalisanumberrepresentedbyonly3bits.Consider a ctitious computer, one that can only do 3-bit binary arithmetic. (Anythingpastthe3rdbitcannotberepresented. SeethenotesforLecture2forsomerelatedexamples.) Completethe following addition table,that is,add the octal inith row totheoctalinthejthcolumnandputtheresultantoctalintheboxlocatedattheithrowandjthcolumn. Thereare3examplesworkedoutforyou. Fortheseexamples,showyourcalculationsinlong-hand.000 001 010 011 100 101 110 111000001010011100101 010110111 011 1102. octal octal=octalThisisasimilarexercisetotheaboveexceptthatyouaretomultiplytheoctals. Besuretoshowyourworkforthe3examplesgiven.000 001 010 011 100 101 110 111000001010011100101 001110111 100 00116 CHAPTER2. DATAREPRESENTATIONS3. Bits,nibblesandintegers. Isitahex?Your imaginary computer representsintegersusing 4 and only 4 bits! The result of anarithmeticoperationwithtwointegersalwaysresultsina4-bitresult. Higher-orderbitsarelost.Thefollowingtableshows thebinary, hexadecimal, unsignedinteger, andunsignedinteger representations for all thepossiblebit patterns that canberepresentedbyyourcomputer.Binary Hexadecimal UnsignedInt SignedInt0000 0 0 00001 1 1 10010 2 2 20011 3 3 30100 4 4 40101 5 5 50110 6 6 60111 7 7 71000 8 8 -81001 9 9 -71010 aorA 10 -61011 borB 11 -51100 corC 12 -41101 dorD 13 -31110 eorE 14 -21111 forF 15 -1Do yourcalculationsin binaryarithmeticand SHOWYOURWORK! Quote yourresults of your calculations in binary, integer, unsigned and hexadecimal integer repre-sentations.(a) Whatisthesumoftheintegers2and3?(b) Whatisthesumoftheintegers-2and-3?(c) Whatisthesumoftheintegers-8and-8?(d) Whatistheproduct oftheintegers2and3?(e) Whatistheproduct oftheintegers-2and-3?(f) Whatistheproduct oftheintegers-8and-8?2.7. PROBLEMS 174. Theinterbreedinghex: hex+hex=hexConsider a ctitious computer, one that can only do 4-bit binary arithmetic. (Anythingpastthe4thbitcannotberepresented. SeethenotesforLecture2forsomerelatedexamples.) Completethefollowingadditiontable,thatis, addthehexinithrowtothehexinthejthcolumnandputtheresultanthexintheboxlocatedattheithrowandjthcolumn. Someoftheanswersaregiventoyou. Fillintheemptyboxes.Remember that addition commutes. Therefore the actual work is halved and you neednotdotheboxesthatarelledwithXs.+ 0 1 2 3 4 5 6 7 8 9 A B C D E F0 0 X X X X X X X X X X X X X X X1 1 2 X X X X X X X X X X X X X X2 2 3 4 X X X X X X X X X X X X X3 3 4 6 X X X X X X X X X X X X4 4 5 8 X X X X X X X X X X X5 5 6 a X X X X X X X X X X6 6 7 c X X X X X X X X X7 7 8 e X X X X X X X X8 8 9 0 X X X X X X X9 9 a 2 X X X X X XA a b 4 X X X X XB b c 6 X X X XC c d 8 X X XD d e a X XE e f c XF f 0 e18 CHAPTER2. DATAREPRESENTATIONS5. Oh,hex,wontiteverstop: hex hex=hexThis is a similar exercise to the previous one except that you are to multiply the hexes.X 0 1 2 3 4 5 6 7 8 9 A B C D E F0 0 X X X X X X X X X X X X X X X1 0 1 X X X X X X X X X X X X X X2 0 2 4 X X X X X X X X X X X X X3 0 3 9 X X X X X X X X X X X X4 0 4 0 X X X X X X X X X X X5 0 5 9 X X X X X X X X X X6 0 6 4 X X X X X X X X X7 0 7 1 X X X X X X X X8 0 8 0 X X X X X X X9 0 9 1 X X X X X XA 0 a 4 X X X X XB 0 b 9 X X X XC 0 c 0 X X XD 0 d 9 X XE 0 e 4 XF 0 f 12.7. PROBLEMS 196. Astfulof(binary)digitsYour imaginarycomputer represents integers using 5andonly5bits! Fill intheblankspotsinthefollowingtable. Thesignedintegersfollowthe2scomplementrulediscussedinclass.Binary Hexadecimal UnsignedInt SignedInt00000 00 0 000001 01 1 100010 02 2 200011 03 3 300100 04 4 400101 05 5 500110 06 6 600111 07 7 701000 08 801001 09 901010 0A 1001011 0B 1101100 0C 1201101 0D 1301110 0E 1401111 0F 1510000 10 1610001 11 1710010 1210011 1310100101011011010111110001100111010110111110011101 -311110 -211111 -120 CHAPTER2. DATAREPRESENTATIONS7. Thesedigitswillgiveyouthedgets.Your imaginary computer still represents integers using 5 and only 5 bits! The result ofan arithmetic operation with two integers always results in a 5-bit result. Higher-orderbitsarelost.Do yourcalculationsin binaryarithmeticand SHOWYOURWORK! Quote yourresults of your calculations in binary, integer, unsigned and hexadecimal integer repre-sentations. Youmayusethetablethatyoucompletedinthepreviousquestion.(a) Whatisthesumoftheunsignedintegers3and4?(b) Whatisthesumoftheunsignedintegers16and17?(c) Whatisthesumofthesignedintegers-2and-3?(d) Whatisthesumofthesignedintegers-16 and-16?(e) Whatistheproduct oftheunsignedintegers3and4?(f) Whatistheproduct ofthesignedintegers-2and-3?(g) Whatistheproduct ofthesignedintegers-16and-16?2.7. PROBLEMS 218. Bitsandbytes?Again!Inthefollowingtable,thecolumn1representsbitpatternsona6-bitcomputer.(a) Inthe2ndcolumn,writeinthecomplementofthebitpatternincolumn1(b) Inthe3rdcolumn,writeinthe2s-complementofthebitpatternincolumn1(c) Inthe4thcolumn,writeinthe2s-complementofthebitpatternincolumn3(d) Inthe5thcolumn,putacheckmarkifthebitpatternincolumn1representsapositivesignedint.(e) In the 6th column, put a checkmark if the bit pattern in column 1 representsanoddunsigned int.(f) In the 7th column, put a checkmark if the bit pattern in column 1 representsanunsigned intthatisdivisibleby2.(g) In the 8th column, put a checkmark if the bit pattern in column 1 representsanunsigned intthatisdivisibleby4.(h) If the bit pattern in column 1 represents an odd unsigned int, write its unsignedintrepresentationincolumn9.Column1 Column2 Column3 Column4 Col5 Col6 Col7 Col8 Column900001011100111011000000100110111001001001011011010111110101022 CHAPTER2. DATAREPRESENTATIONS9. AbitchallengingInthefollowingtable:1)Converttherst532-bit bitpatternstohex2)indicatewhichbitpatternsaredivisibleby2(/2)3)indicatewhichbitpatternsaredivisibleby4(/4)4) indicate which bit patterns represent positive or negative integers in 2s complementrepresentation(+/-?)5)indicatewhichbitpatternrepresentsthelargestintegerin2scomplementrepre-sentation(>?)6)indicatewhichbitpatternrepresentsthesmallestintegerin2scomplementrepre-sentation,negativewiththegreatestmagnitude(