9200134_CH00_FM_pi-viii.qxd 6/23/09 3:08 AM Page i Workbook for C++ THIRD EDITION Yedidyah Langsam, Ph.D. Brooklyn College of the City University of New York Custom Publishing New York Boston San Francisco London Toronto Sydney Tokyo Singapore Madrid Mexico City Munich Paris Cape Town Hong Kong Montreal
9200134_CH00_FM_pi-viii.qxd 1/1/70 10:54 AM Page ii Copyright 2009, 2007, 1997 by Yedidyah Langsam All rights reserved. Permission in writing must be obtained from the publisher before any part of this work may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying and recording, or by any information storage or retrieval system. All trademarks, service marks, registered trademarks, and registered service marks are the property of their respective owners and are used herein for identification purposes only. Printed in the United States of America 10 9 8 7 6 5 4 3 2 1 2009200134 MP www.pearsonhighered.com ISBN10:0-558-34753-3 ISBN13:978-0-558-34753-6
9200134_CH00_FM_pi-viii.qxd 1/1/70 10:54 AM Page iii CONTENTS To the Student v CHAPTER 1 Introduction to Computers and C++ Programming 1 SECTION 1.1 Computers 1 SECTION 1.2 Programming and Problem Solving 6 SECTION 1.3 C++ Programming Projects 9 CHAPTER 2 C++ Basics 11 SECTION 2.1 Identifiers and Keywords 11 SECTION 2.2 Arithmetic Expressions 12 SECTION 2.3 Arithmetic Precedence 15 SECTION 2.4 Standard (cmath) Library Functions 20 CHAPTER 3 Conditional Branching 25 SECTION 3.1 if and if-else Statements 25 SECTION 3.2 Nested if-else Statements 26 SECTION 3.3 Logical and Relational Operators 28 SECTION 3.4 Integer and Logical Values 33 CHAPTER 4 Flowcharts 37 CHAPTER 5 Loops 45 SECTION 5.1 while Loops 45 SECTION 5.2 for Loops 60 SECTION 5.3 More Complex Loops 64 SECTION 5.4 do-while Loops 66 SECTION 5.5 break and continue Statements 68 SECTION 5.6 switch Statements 71 CHAPTER 6 C++ Input/Output 75 SECTION 6.1 Writing to the Screen (stdout) 75 SECTION 6.2 Read Interactively from the Keyboard (stdin) 79 SECTION 6.3 Reading and writing from Files 80 CHAPTER 7 Integer and Character Variables 81 CHAPTER 8 Functions 87 SECTION 8.1 Functions: Using Value Parameters 87 SECTION 8.2 Functions: Using Reference Parameters 94 SECTION 8.3 Using Arrays in Functions 102 CHAPTER 9 Arrays 109 SECTION 9.1 One-Dimensional Arrays 109 SECTION 9.2 Two-Dimensional Arrays 118 SECTION 9.3 Arrays with Functions 125 CHAPTER 10 Sorting and Searching 127 SECTION 10.1 Sorting 127 SECTION 10.2 Searching 128 CHAPTER 11 String Manipulation in C++ 131 SECTION 11.1 String Representation 131 SECTION 11.2 The string Library 134 CHAPTER 12 Classes 139 SECTION 12.1 Simple Classes (Without Member Functions) 139 SECTION 12.2 Classes (With Member Functions) 150 SECTION 12.3 Constructors and Destructors 153 CHAPTER 13 Pointers and Indirection 157 CHAPTER 14 Number Systems 161 SECTION 14.1 Decimal 161 SECTION 14.2 Binary and Hexadecimal 161 iii
9200134_CH00_FM_pi-viii.qxd 1/1/70 10:54 AM Page iv iv Contents SAMPLE FINAL EXAMINATION ONE 163 SAMPLE FINAL EXAMINATION TWO 169 ANSWERS 175 CHAPTER 1 Introduction to Computers and C++ Programming 175 CHAPTER 2 C++ Basics 178 CHAPTER 3 Conditional Branching 185 CHAPTER 4 Flowcharts 193 CHAPTER 5 Loops 195 CHAPTER 6 C++ Input/Output 203 CHAPTER 7 Integer and Character Variables 208 CHAPTER 8 Functions 211 CHAPTER 9 Arrays 222 CHAPTER 10 Sorting and Searching 234 CHAPTER 11 String Manipulation in C++ 238 CHAPTER 12 Classes 243 CHAPTER 13 Pointers and Indirection 257 CHAPTER 14 Number Systems 258 Sample Final Examination One 260 Sample Final Examination Two 263 APPENDIX APPENDIX ONE C++ Keywords 269 APPENDIX TWO C++ Operator Precedence and Associativity 271 APPENDIX THREE ASCII Character Set 273 APPENDIX FOUR Selected Library Functions & Methods 275
9200134_CH00_FM_pi-viii.qxd 1/1/70 10:54 AM Page v TO THE STUDENT To learn to write computer programs, you must learn to devise algorithms plans of attack to solve the problems that you will be given. After that, you must write the program precisely to carry out your plan. Planning the program is the most important part of the programming process. First, plan your algorithm carefully. Ask yourself what techniques you have learned which pertain to this problem. Ask yourself how you would do this problem without a computer. Break the problem into smaller parts, if possible, and plan the large picture first, leaving the details for later consideration. Working problems in this book will give you practice in using the techniques of the C++ language. That practice will help you when you are planning algorithms, and it will help you write programs more effectively. With sufficient practice, you will know which technique to use to solve a particular problem. Repeated practice with the problems will lessen chances for errors in the programs you submit, and save you time in correction and resubmission. (No one can write error-free programs the first time every time, however.) The problems in this book will also prepare you for similar problems on examinations. ORGANIZATION OF THE BOOK This book is divided into four parts. Part I contains sets of problems on various basic topics that every programming language contains. Part II contains sets of problems on advanced topics. These two parts are the heart of the book. Most problems should take you only a few minutes or less. If you cannot do a problem in 10 to 15 minutes, seek help from a tutor or from your instructor. Some of the problems point out pitfalls to avoid in your programs other problems consist of two or more parts which look alike but which actually contain significant differences. Be on the alert so that you recognize the differences between these types of program segments. Occasionally, exercises are preceded by an asterisk (*) indicating that they contain advanced concepts that may be deferred until later on in the semester. Your instructor may organize his/her lectures in a different order than the chapters in this section and may therefore assign specific exercises for you to do. Part III contains two complete sample Brooklyn College final examinations. Typically, final exams at Brooklyn College are two hours in length and are uniform for all students taking the first course. You will be required to trace programs as well as to write programs of your own. Near the end of the semester, you should test yourself on one of the portions of the final exams given here to see that you can not only do the problems but also that you can do them in the limited time available. The format of your final exam may differ from that which is given here. Ask your instructor whether additional sample final examinations are available. Part IV contains tables of C++ Keywords, Precedence of Operators, the ASCII Character set and some library functions. Answers to the problems in Parts I to III are given at the end of the text. Do not look at the answers until you have seriously attempted the problems yourself. Otherwise, it is very easy to trick v
9200134_CH00_FM_pi-viii.qxd 1/1/70 10:54 AM Page vi vi To The Student yourself into believing that you understand a concept when you see the answer; it may be a different matter when you have to generate the answer yourself. There is more than one way to do many computer assignments. If a method is presented in the solution which is different from your method, it is not necessarily true that your method is wrong. Compare the methods to see if you can tell why the printed answer is better, or worse, than yours. Are the methods equivalent? Will they both work with all kinds of data? If your answer is incorrect, try to learn from your mistake. You may learn a new algorithm from the answer given if you did not do the problem in the same way. TYPES OF ERRORS There are many types of errors in computer programming. Syntax errors, or compilation errors, which include the use of incorrect punctuation, incorrect keywords, etc., will be identified by the compiler during compilation. The C++ compiler will try to guess what error occurred but its guess is not necessarily correct. You can be sure that an error has been made at the point specified or immediately before that point. Knowing where the error is makes it easier to correct it and submit the program again. Never submit a program for grading which has errors in it. A second type of error is an execution or run-time error. These errors involve asking the computer to do something which it cannot do. For example, if you ask the computer to divide by a variable which has a current value of zero, an execution error will result. The C++ compiler will show you where the error occurred, which is a big help in trying to correct it. Logical errors are usually more difficult to find and more difficult to correct. These errors usually arise when the programmer does not understand the nature of the problem which is to be solved, or inadvertently gives the computer incorrect instructions to follow. For example, omitting the minus sign in a statement such as x = y; will be undetected by the computer. Unless some following use of the value produced (such as taking the square root of the answer) allows distinction between the value wanted and that produced, the computer has no way of telling that the minus sign has been omitted. However, an incorrect answer will be produced. You should check by hand at least several of the answers produced by the computer to see that your code is written correctly. Some errors will not occur with some data, but will show up with other data. For example, if you want to take the square root of x, the correct answer may appear whenever x is positive but an error will occur when x is negative. Try to test your programs with a wide variety of values to ensure that they will work with all kinds of data. An error frequently encountered is an infinite loop. Infinite loops are often generated by logical errors which have made the computer repeat a set of instructions again and again. You might see nothing at all happening at your computer. (The same symptom is produced when the computer is waiting for you to enter some data.) You might put some cout statements into your program temporarily so that some action is taken by the computer while it is in the loop, allowing you to diagnose what is happening. In fact, such temporary cout statements are an effective way to debug a program no matter what types of errors are involved. ACKNOWLEDGMENTS First and foremost, I would like to thank Professor David E. Goldberg and Professor Keith Harrow my co-authors on previous versions of this book, PL/I and PL/C Workbook and Workbook for Pascal for permission to use many of the exercises in those books. In addition, Professor Harrow spent many additional hours proofreading early drafts of this book and offered many helpful suggestions. A special thank you to Professor Eva Cogan for finding many of the errors in the text. Of course any errors that remain are the responsibility of the author. I am grateful to Professors David
9200134_CH00_FM_pi-viii.qxd 1/1/70 10:54 AM Page vii To The Student vii Arnow, Keith Harrow, Jacqueline A. Jones and Gerald Weiss for their many suggestions regarding C++ programming style. All the programs in this text have been tested and debugged. Programs given in this book have been developed using the Dev-C++ 5.0 beta 9.2 (4.9.9.2) with Mingw/GCC 3.9/3.4.2 which is freely available at http://www.bloodshed.net/index.html. Readers are encouraged to download this compiler in order to develop their own programs. Another highly recommended freely available C++ IDE can be found at http://www.codeblocks.org. The author wishes to thank Mr. Raheel Zamir for his invaluable assistance in this task. Mr. Zamir has also contributed many of the exercises that have been introduced in this edition of the text. To my wife, Vivienne, and my children, I offer special thanks for their forbearance during the summer, which was lost to them by my full time commitment to this book.
9200134_CH00_FM_pi-viii.qxd 1/1/70 10:54 AM Page viii