Introduction to Computers and Programming Using C++ and MATLAB
Total Page:16
File Type:pdf, Size:1020Kb
Introduction to Computers and Programming using C++ and MATLAB Alex F. Bielajew The University of Michigan Department of Nuclear Engineering andRadiologicalSciences 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—2010 Alex F Bielajew Revision: October 12, 2010 2 Preface This “book” arises out of a course I teach, a four-credit (52 hour) freshman-level course Introduction to Computers and Programming being taught in the College of Engineering at the University of Michigan. The book is in reasonably rough shape at this stage. It was assembledfrom my lecture notes several years ago andis under constant revision. I may never finish it! A wise person once said, “Old age happens when you dwell more on the past than on the future.” By this definition, I have found eternal youth, insofar as this book is concerned. My educational objectives are quite simple. This is not really a course in computing. It is a course in thinking, technical thinking, logical thinking, about formulating a problem, a mathematical problem, a physics problem, a game, andthen executing a solution andmaking it “work”. I consider the computer and the ability to program it as a kind of laboratory—a laboratory to investigate practically, the theories andideasof other technical courses. It is possible, for example, to teach a lot of Calculus to students without ever mentioning the word, and there are several examples throughout this book. This course is not about syntax. Hence, the book introduces the minimum amount syntax to get through a problem. Indeed, I even keep some syntax hidden, to encourage students to discover their own algorithms. So, if you are thinking of using this book as a technical reference in C++ or Matlab, I anticipate that you will be disappointed. The greatest value in this book, if there is any to be found, is in the exercises, problems and projects at the back of almost every chapter. The ideal way to learn a computer language is to learn a little syntax andthen try it out on a computer. The idealway to think is not to readabout it, but to actually doit! The book reflects this. The material in the chapters, separatedfrom the exercises, is worse than useless, for readingthe material and not doing the problems is just a waste of time. Do the problems! Moreover, don’t ask me for the solutions! There is much more pedagogical value in a well-posed question than a well-articulatedanswer. OK, I’ll step off my soap box now! Several professors and many students have contributed to the ideas put into this book. Professor James Holloway and I have had endless discussion on the general problem of teaching algorithmic thinking to freshman. We still have not come to any conclusions except i ii that it is highly challenging and rewarding. As for how it actually gets done, well, to be sure it is a works-in-progress. I spent a very enjoyable term co-teaching this course (the first time I taught it) with Professor Ken Powell. Thanks, Ken, for nursing me through that first year! Both James’s and Ken’s diverse computational backgrounds are reflected to some degree in this book. I owe a debt of gratitude to the dozens of Graduate Student Instructors who have taught with me on this course. One of them, Dan Osborne, deserves special recognition. He is one of the most giftedandcommittedteachers I have ever encountered. Dan andI spent hour after hour discussing the challenges of teaching computing and thinking skills to undergraduates. To the 3000 or so undergraduates, mostly freshmen, who have taken my course: Every time I teach this course I learn something new—about computing, about teaching, about the joy of making an early “deflection” in a student’s career. Finally, I am one of those people who tends to see the forest, instead of the trees. Conse- quently, spelling andsentence structure usually yieldto an enthusiasm to present the material in an interesting way. It’s not my only fault, but maybe my most visible one. To this end, please inform me if you spot any errors. I am also deeply indebted to my wife-to-be, Linda Park, for her unimaginable attention to detail, her proofreading and suggestions. Linda, every time you undertake a proofreading project on my behalf, my mind boggles, truly. AFB, October 12, 2010 Contents 1 Introduction to the course 1 1.1Whatthiscourseisabout............................ 1 1.2Problems...................................... 6 2 Data representations 7 2.1Bits,nibbles,bytesandwords.......................... 7 2.24-bitBinary,HexadecimalandDecimalDigits................. 9 2.3Binaryarithmetic................................. 9 2.4Convertingfrombinarytodecimal....................... 10 2.4.1 Wholenumbers.............................. 10 2.4.2 Realnumbers............................... 11 2.5Binaryintegerarithmeticoncomputers..................... 11 2.5.1 Two’s-complementintegerarithmetic.................. 12 2.632-bitBinary,Hexadecimal,UnsignedandSignedIntegers.......... 13 2.7Problems...................................... 15 3 Algorithms and Pseudocodes 23 3.1Whatisanalgorithm?.............................. 23 3.2Flowchartrepresentation............................. 24 3.3Pseudocoderepresentation............................ 24 3.4Decisions,conditionals,branchinstructions .................. 25 3.5Loopingorjumpinstructions.......................... 25 iii iv CONTENTS 3.6Sequencing,branchingandlooping....................... 26 3.7Amini-summarybeforetheexamples...................... 27 3.8Someexamples.................................. 27 3.8.1 The Breakfast algorithm, or, Bielajew’s Sunday Morning Internationally- famouspancakes............................. 28 3.8.2 Solve for x: Ax2 + Bx + C =0whereA, B, C are arbitrary constants 29 3.8.3 Iteration:Asummingloop........................ 33 3.8.4 Iteration:Aproductloop........................ 36 3.9Anasideoncomputerarchitecture....................... 40 3.9.1 What does S = S +1mean?....................... 40 3.10Problems...................................... 41 3.11Projects...................................... 47 4 Getting started in C++ 49 4.1 Simple input/output (I/O): A first program in C++ .............. 49 4.2 Compiling, linking, loading and running .................... 52 4.3Declaringandinitializingvariables....................... 55 4.4IntegermathinC++............................... 57 4.5FloatingpointmathinC++........................... 59 4.6 The if/else if/else construct......................... 60 4.7Logicalexpressions................................ 63 4.7.1 LogicalexpressionswithANDorOR.................. 66 4.7.2 Mixedarithmeticandlogicalexpressions................ 67 4.8Problems...................................... 69 4.9Projects...................................... 73 5Loops 83 5.1 The while loop.................................. 83 5.2 The do/while loop................................ 86 5.3 The for loop................................... 89 CONTENTS v 5.4Problems...................................... 94 5.5Projects...................................... 111 6 Early Abstraction—Functions 123 6.1Motivationforfunctions............................. 123 6.2User-definedfunctions.............................. 129 6.3Example:Aproblemtackledwithteamwork.................. 134 6.4Callbyvalue,callbyreference,referenceparameters............. 138 6.4.1 Theaddressofavariable......................... 138 6.4.2 Call-by-value vs. call-by-reference.................... 140 6.5Therulesofscope................................. 145 6.6Problems...................................... 153 6.7Projects...................................... 160 7 More Variable Types, Data Abstraction 167 7.1Representationoffloating-pointnumbers.................... 167 7.1.1 Whenisonenotone?Floatingpointanomalies............. 174 7.2 char:thecharactervariable........................... 175 7.2.1 Characterstrings;thestringclass.................... 177 7.3Thevectorclass.................................. 179 7.3.1 Introductiontovectors.......................... 179 7.3.2 Declaringandusingvectors....................... 180 7.3.3 Vectorsyntaxandrules:......................... 182 7.3.4 Vectorsandfunctions........................... 187 7.4Problems...................................... 189 8 More Data Abstraction, Arrays, Structures 199 8.1Arrays....................................... 199 8.1.1 Declaringa2-dimensionalarray..................... 200 8.1.2 Initializinga2-dimensionalarray.................... 201 vi CONTENTS 8.1.3 Passingatwo-dimensionalarraytoafunction............. 204 8.2Characterarrays................................. 209 8.2.1 Onedimensionalcharacterarrays.................... 209 8.2.2 Twodimensionalcharacterarrays.................... 211 8.3Structures..................................... 211 8.3.1 Thestructuredefinition......................... 212 8.3.2 Wherecanstructuresbedefined?.................... 213 8.3.3 Themembersofastructure....................... 213 8.3.4 Declaringstructurevariables....................... 213 8.3.5 Assigningvaluestostructuremembers................. 213 8.3.6 Re-assigningvaluesofstructuremembers................ 214 8.3.7 Functioncall-by-valueofastructure.................. 214 8.3.8 Functioncall-by-referencetoastructure................ 215 8.3.9 Structurearrays.............................. 215 8.3.10Exampleusingstructuresandarrays:Iontransport.......... 218 8.4Problems...................................... 222 8.5Projects...................................... 228 9 Miscellaneous