Workbook for C++ THIRD EDITION. Yedidyah Langsam, Ph.D. Brooklyn College of the City University of New York. Custom Publishing

Similar documents
Prelude to Programming

MariaDB Crash Course. A Addison-Wesley. Ben Forta. Upper Saddle River, NJ Boston. Indianapolis. Singapore Mexico City. Cape Town Sydney.

Programming in Python 3

CLASSIC DATA STRUCTURES IN JAVA

Database Concepts. David M. Kroenke UNIVERSITATSBIBLIOTHEK HANNOVER

THE AVR MICROCONTROLLER AND EMBEDDED SYSTEMS. Using Assembly and С

This page intentionally left blank

DATA ABSTRACTION AND PROBLEM SOLVING WITH JAVA

ony Gaddis Haywood Community College STARTING OUT WITH PEARSON Amsterdam Cape Town Dubai London Madrid Milan Munich Paris Montreal Toronto

HCS12 Microcontroller and Embedded Systems: Using Assembly and C with CodeWarrior 1 st Edition

An Introduction to Programming with IDL

LATEX. Leslie Lamport. Digital Equipment Corporation. Illustrations by Duane Bibby. v ADDISON-WESLEY

Objects First with Java

C for Electronic Engineering

PROBLEM SOLVING USING JAVA WITH DATA STRUCTURES. A Multimedia Approach. Mark Guzdial and Barbara Ericson PEARSON. College of Computing

World Wide Web PROGRAMMING THE PEARSON EIGHTH EDITION. University of Colorado at Colorado Springs

Visual C# Tony Gaddis. Haywood Community College STARTING OUT WITH. Piyali Sengupta. Third Edition. Global Edition contributions by.

Chapter 2 Basic Elements of C++

Introduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p.

Programming. In Ada JOHN BARNES TT ADDISON-WESLEY

Absolute C++ Walter Savitch

Introduction to Programming using C++

Programming Fundamentals - A Modular Structured Approach using C++ By: Kenneth Leroy Busbee

Computer Programming C++ (wg) CCOs

DB2 SQL Tuning Tips for z/os Developers

SAULT COLLEGE OF APPLIED ARTS AND TECHNOLOGY SAULT STE. MARIE, ONTARIO. Sault College COURSE OUTLINE CODE NO. : CSD100 SEMESTER: 1

EMBEDDED SYSTEMS: Jonathan W. Valvano INTRODUCTION TO THE MSP432 MICROCONTROLLER. Volume 1 First Edition June 2015

Curriculum Map Grade(s): Subject: AP Computer Science

SQL Queries. for. Mere Mortals. Third Edition. A Hands-On Guide to Data Manipulation in SQL. John L. Viescas Michael J. Hernandez

PROGRAMMING AND CUSTOMIZING

How & Why We Subnet Lab Workbook

HUDSON VALLEY COMMUNITY COLLEGE TROY, NEW YORK COURSE OUTLINE

CoSci 440 SYLLABUS Programming in C++ INSTRUCTOR Mari Rettke cell SECTION : and 13345

Course Text. Course Description. Course Objectives. StraighterLine Introduction to Programming in C++

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are:

Constructing Algorithms and Pseudocoding This document was originally developed by Professor John P. Russo

Updated: 2/14/2017 Page 1 of 6

An Object Oriented Programming with C

STUDENT OUTLINE. Lesson 8: Structured Programming, Control Structures, if-else Statements, Pseudocode

[CHAPTER] 1 INTRODUCTION 1

Creating a procedural computer program using COBOL Level 2 Notes for City & Guilds 7540 Unit 005

PYTHON. p ykos vtawynivis. Second eciitiovl. CO Ve, WESLEY J. CHUN

Practical C++ Programming

The print queue was too long. The print queue is always too long shortly before assignments are due. Print your documentation

Data Structures and Abstractions with Java

Real-Time Systems and Programming Languages

A Document Preparation System. User's Guide and Reference Manual. Leslie Lamport

EECE.2160: ECE Application Programming Spring 2019

Data Structures and Abstractions with Java

Using MATLAB, SIMULINK and Control System Toolbox

Understanding and Writing Compilers

To become familiar with array manipulation, searching, and sorting.

PESIT-BSC Department of Science & Humanities

Bits, Words, and Integers

Interfacing with C++

Mathematics/Science Department Kirkwood Community College. Course Syllabus. Computer Science CSC142 1/10

The Unified Modeling Language User Guide

Overview : Table Of Content :

Course materials Reges, Stuart, and Stepp, Martin. Building Java Programs: A Back to Basics Approach. 2d ed. (Boston: Addison-Wesley, 2011).

Lecture 1 Getting Started with SAS

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #44. Multidimensional Array and pointers

Bash Programming. Student Workbook

C++ Programming for Non-C Programmers. Supplement

Chapter 2.6: Testing and running a solution

CS143 Handout 05 Summer 2011 June 22, 2011 Programming Project 1: Lexical Analysis

Welcome to Starting Out with Programming Logic and Design, Third Edition.

Problem Solving with C++

Lecture 5. Review from last week. Selection Statements. cin and cout directives escape sequences

Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Assembly Language Assembled for the Sinclair ZX81

Access ComprehGnsiwG. Shelley Gaskin, Carolyn McLellan, and. Nancy Graviett. with Microsoft

This course supports the assessment for Scripting and Programming Applications. The course covers 4 competencies and represents 4 competency units.

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

College Board. AP CS A Labs Magpie, Elevens, and Picture Lab. New York: College Entrance Examination Board, 2013.

3. Simple Types, Variables, and Constants

بسم اهلل الرمحن الرحيم

CS 241 Data Organization using C

Xcode 6 Start to Finish

Introduction to Programming Using Java (98-388)

MASTERING COBOL PROGRAMMING

C++ Programming for Non-C Programmers. Supplement

Topic 1: Programming concepts

MECHATRONICS. William Bolton. Sixth Edition ELECTRONIC CONTROL SYSTEMS ENGINEERING IN MECHANICAL AND ELECTRICAL PEARSON

JAVASCRIPT FOR PROGRAMMERS

CIS 130 Exam #2 Review Suggestions

PROBLEM SOLVING WITH FORTRAN 90

JAVASCRIPT AND JQUERY: AN INTRODUCTION (WEB PROGRAMMING, X452.1)

Modesto Junior College Course Outline of Record CMPSC 241

QUIZ How do we implement run-time constants and. compile-time constants inside classes?

Introduction to Programming System Design CSCI 455x (4 Units)

ENGINEERING PROGRAMMING

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

3D Graphics Programming Mira Costa High School - Class Syllabus,

DATA AND COMPUTER COMMUNICATIONS

Integrated Approach. Operating Systems COMPUTER SYSTEMS. LEAHY, Jr. Georgia Institute of Technology. Umakishore RAMACHANDRAN. William D.

Object-Oriented Programming and Data Structures

Fundamentals of. Database Systems. Shamkant B. Navathe. College of Computing Georgia Institute of Technology PEARSON.

CSE100 Principles of Programming with C++

Designing Loops and General Debug Pre-Defined Functions in C++ CS 16: Solving Problems with Computers I Lecture #6

Transcription:

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