Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Solutions to the Exercises from ""Programming Principles and Practice Using C++"" by Bjarne Stroustrup

NotificationsYou must be signed in to change notification settings

Ziezi/Programming-Principles-and-Practice-Using-C-by-Bjarne-Stroustrup-

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

20 Commits
 
 
 
 
 
 
 
 

Repository files navigation

Exercises from

"Programming Principles and Practice Using C++"

Chapter 1

  1. Compile a list of daily activities involving the use of computers.
  2. Pick a favourite profession and the activities within it involving the use of computers.
  3. Swap the lists from Ex 1 and Ex 2 with a friend and compare results.
  4. List of activities not possible without computers.
  5. List of programs that you have used.
  6. List of activities not involving computers.
  7. Five tasks for which computers will be used in the future.
  8. Why do you like to be a programmer? ($100 < words < 500$)
  9. What other role in computer industry do you like to play?
  10. Do you think computers will ever be developed to be conscious, thinking, capable of competing with humans?
  11. List of characteristics that good programmers share.
  12. Identify five applications for computer programs mentioned in the chapter and one that you want to participate in.
  13. How much memory would it take to store: this page, text, Shakespeare's work. (1 byte == 1 character; Estimate 20% precision)
  14. How much memory (main, disk) does your computer have?

Chapter 2

  1. Print"Hello, programming!\nHere we go!".
  2. Write pseudo code (instructions) directing "the computer" upstairs to the bathroom.
  3. Write pseudo code (instructions) directing "the computer" from your house/dorm to work/university.
  4. Write instructions for a food cooking recipe.
  5. Write definition of each of the new terms covered in the first chapter.

Chapter 3

  1. Do allTry This examples in the chapter.
  2. Miles to kilometers converter.
  3. Check compiler response to illegal variable names (identifiers).
  4. Define and read twoints. Find and print theirmin,max,sum,difference,product andratio.
  5. Redo the Exercise 4 with floating point number variablesdouble.
  6. Read threeints and list them in increasing order.
  7. Redo Exercise 6 withstrings.
  8. Check ifint isodd oreven.
  9. Read anint as digit / name and print it as name / digit.
  10. Read an operation (+, -, *, /) and two (double) values and print the result. (Useif statements).
  11. Readpennies, nickels, dimes, quarters andhalf dollars and print total sum ofcents.

Chapter 4

  1. Do allTry This examples in the chapter.
  2. Findmedian (element in the middle of the sorted set). Modify4.6.2
  3. Readdouble values and store them into avector. Findtotal sum,mean of all elements,min andmax.
  4. Write a number guessing game. (manualBinary seach usingif statements).
  5. Implement asimple calculator with few operations$(+, -, *, /, %)$.
  6. Store the names of the digits [0, 9] in avector and use it to convert digit to its name.
  7. Modify Exercise 5 to accept either single digit or its name.
  8. CalculateExponential growth aftern turns.
  9. Largest value held inint ordouble,overflow.
  10. Implement a game"Rock, Paper, Scissors.". (useswitch statements)
  11. Findprime numbers within$[1, 100]$. (Usevector that holds current previous primes.)
  12. Findprime numbers within$[min, max]$.
  13. ImplementSieve of Eratosthenes within$[1,100]$.
  14. Modify Exercise 13 to interval$[min, max]$.
  15. Find firstnprimes.
  16. Find themode of a sequence of positiveints.
  17. Findmin,max andmode of sequence ofstrings.
  18. Solve thequadratic equation with coefficientsa,b andc.
  19. Readname andvalue pairs. Check name uniqueness.
  20. Modify Exercise 19, so that when you typename it prints itsvalue.
  21. Modify Exercise 19, so that when you type anint value it prints the names with that score.

Chapter 5

  1. Do allTry This examples in the chapter.
  2. Debug existingCelsius toKelvin converter.
  3. Choose appropriatemin value and modify Ex. 2.
  4. Handle the errors withinctok().
  5. Write aKelvin toCelsius converter.
  6. Write aCelsius$<=>$Fahrenheit converter. (Estimate result.)
  7. Solve thequadratic equation,throw an exception ifdiscriminant< 0.
  8. Readints (quit with|), store them in avector and prompt the user to sumn of them.
  9. Modify Ex. 8 and display error if result can't be stored inint.
  10. Redo Ex. 8 with values of typedouble. Calculate thedifferences of adjacent elements.
  11. Print the firstnFibonacci numbers. Find largest Fibonacci stored inint.
  12. Implement"Bulls and Cows".
  13. Redo Ex. 12, but let each time the numbers be random. (Userand() andsrand())
  14. Read(day-of-the-week, value) pairs and store each day in avector<int>. Print each day and its values.

Chapter 6

  1. Do allTry This examples in the chapter.
  2. Modify thecalculator to evaluate expressions containing$(,)$ and${,}$.
  3. Add factorial operator!.
  4. Rework Ex. 19 Ch. 4 using aclass Name_value.
  5. Expand theEnglish Grammar from6.4.1 to includethe.
  6. Write a program that checks if sentence is correct according to theEnglish Grammar.
  7. Write aGrammar for Logical Epxressions.
  8. Redo"Bulls and Cows" from Ex. 12 Ch. 5, to use four letters instead of four digits.
  9. Write a program that reads digits and composes them into integers.
  10. Calculatepermutations P(a, b) andcombinations C(a, b).

Chapter 7

  1. Allow underscore_ in the names of the user defined variable in thecalculator.
  2. Allow used defined variable value reassignment, by introducing an assignmentoperator=.
  3. Allow the definition ofconst variables.
  4. Defineclass Symbol_table and rewrite the calculator to use it.
  5. Print result at newline\n.
  6. Providehelp function in the calculator.
  7. Changehelp andquit commands.
  8. Fix the calculator grammar and add comments (document the code).
  9. Define aclass Table and rewrite the calculator to use it.
  10. Suggest three improvements and implement one.
  11. Modify the calculator to operate onint only.
  12. Discuss the possible source of problems of introduction of assignmentoperator=.
  13. Revisit two programs from Ch. 4 and Ch. 5, clean and comment them.

Chapter 8

  1. Modify thecalculator to make the input stream an explicit parameter. GiveToken_stream constructor aistream& parameter.
  2. Write a functionprint() that prints avector ofints; Include astring parameter label.
  3. FindnFibonacci numbers and store them in avector. Use functionprint() from Ex. 2 to print them.
  4. Find the largestFibonacci number stored inint.
  5. Write a function thatreverses theint elements of avector.
  6. Redo Ex. 5 usingstrings.
  7. Read fivenames and fiveages. Sort thenames and match theages. Print the result.
  8. Implement a simple functionrandint().(SeeKnuth, The Art of Computer Programming, Volume 2)
  9. Write a functionrand_in_range(int a, int b) that generates a pseudo-random number within$[a, b)$, usingrandint().
  10. Write a function that calculates thesum of the products of the elements of twovectors. (Allow one vector with smaller size).
  11. Write a functionmaxv() that returns the largest element of a vector argument.
  12. Findmin,max,mean andmedian of vector arguments. Return the result usingstruct or bypassing by reference.
  13. Improveprint_until_s() from8.5.2. Test it. Write a functionprint_until_ss() that prints until the second occurrence of its argumentquit.
  14. Write a function that takes avector<string> argument and returnsvector<int> containing the number of character in eachstring. Also findlongest andshortest, lexicographically first and laststrings.
  15. Can we declare a non-reference function argumentconst? Why would we? Test it.

Chapter 9

  1. List sets of plausible operations for the examples of real-world objects in§9.1 (such as toaster).
  2. Design and implement aName_pairs, holding (string name, double age). Providesort() operation.
  3. ReplaceName_pair::print() with a (global)operator<< and define== and!= forName_pairs.
  4. Indent the code from§8.4.
  5. Implement aclass Book, such as you can imagine as part of software for a library; with members for theISBN,title,author, andcopyright date. Create appropriate member functions.
  6. Add operators==,<< for theclass Book.
  7. Create anenum type for theclass Book calledGenre. Have the types befiction,nonfiction,periodical,biography,children.
  8. Create aclass Patron for tlle library. The class will have auser's name,library card number, andlibrary fees (if owed). Create appropriate member functions.
  9. Create aclass Library. Include vectors ofBooks andPatrons. Include astruct calledTransaction. Have it include aBook, aPatron, and aDate. Create appropriate member functions.
  10. Implementleapyear() from§9.8.
  11. Design and implement a set of useful helper function for theclass Date such asnext_workday() andweek_of_year().
  12. Change the representation of aDate to be the number of days sinceJanuary I, 1970 (known as day 0), represented as along, and reimplement the functions from§9.8.
  13. Design and implement a rational numberclass Rational.
  14. Design and implement aclass Money for calculations involvingdollars andcents where arithmetic has to be accurate to the lastcent usingthe 4/5 rounding rule.
  15. Refine theclass Money by adding acurrency. Provide a conversion table.
  16. Give an example of a calculation where aRational gives a mathematically better result thanMoney.
  17. Give an example of a calculation where aRational gives a mathematically better result thandouble.

Chapter 10

  1. Sum of all the numbers in a file of whites space-separated integers.
  2. Creates a file of data in the form of the temperatureReading type defined in §10.5. Fill the file with at least 50 temperature readings.
  3. Create a program that reads the data created inExercise 2 into avector and then calculates the mean and median of the temperatures in your data set.
  4. ModifyExercise 2 to include temperature unit suffixC - Celsius orF - Fahrenheit. Modify the function fromExercise 3 to firstly convert the temperature in Fahrenheit before calculating the statistics.
  5. Write the functionprin_year() mentioned in §1O.11.2.
  6. Define aRoman_int class for holding Roman numerals (as ints) with aoperator<< and>> . ProvideRoman_int with anas_int() member.
  7. Make a version of the calculator fromChapter 7 that accepts Roman numerals.
  8. Write a program that accepts two file names and produces a new file that concatenates the two files.
  9. Write a program that takes two files containing sorted white space-separated words and merges them, preserving the order.
  10. Add a commandfrom x to the calculator fromChapter 7 that makes it take input from a filex. Add a commandto y that makes it write its output (both standard output and error output) to filey. Write a collection of test cases based on ideas from §7.3 and use that to test the calculator.
  11. Write a program that produces the sum of all the white space-separated integers in a text file.
  12. Write a program that given a file name and a word outputs each line that contains that word together with the line number.

Chapter 11

  1. Read a file, convert to lower case and write to another file.
  2. Remove all the vowels from a text file.
  3. Write a program that correctly interprets the base prefixes of integers, i.e. decimal (none), octal (0), hexadecimal (0x), converts them to decimal and prints them in a table in their initial and final format.
  4. Read a string and classify each of its characters, e.g.isalpha(),isspace(), etc.
  5. Replace punctuation with white space.
  6. Modify Ex. 5 to replacedon't withdo not andcan't withcannot; to leave hyphens in between words intact.
  7. Use the knowledge from the previous exercises to create a dictionary from a multi-page text.
  8. Read and write a binary file.
  9. Write a function that accepts a string and returns a vector holding all the white space separated sub-strings of the argument.
  10. Expand Ex. 9 to include sub-string separation at any character passed as an additional argument.
  11. Reverse the order of characters in a text file.
  12. Reverse the order of words (white space separated) in a text file.
  13. Perform character classification on the contents of a text file.
  14. Read a file containing integers, format them to scientific representation with precision up to the eight digit after the decimal point and write them to another file, four per line in fields of width of 20 characters.
  15. Read a file containing integers, sort, count write the result in a table in another file.

Chapter 12

  1. Drill: Introduction to reduced GUI based on FLTK: include needed libraries, createSimple_window.
  2. Create a rectangle using classRectangle and classPolygon, use different colours.
  3. Draw aRectangle and place aText object inside it.
  4. DraW your initials in different colours.
  5. Draw a Checkers board, with white and red squares.
  6. Draw a red 1/4-inch frame around a rectangle that is 3/4 the height and 2/4 the width of the screen.
  7. Draw aShape not matching the size of the window andWindow not matching the size of the of the screen.
  8. Draw a picture of a house.
  9. Draw the Olympic five rings.
  10. Display an image and manipulate it.
  11. Draw the file diagram of Chapter 12.8, describing the hierarchy of source code dependencies.
  12. Draw a series of polygons, one inside the other.
  13. Draw a "star-like" pattern by connecting points of super-ellipse.
  14. Draw super-ellipses of multiple colours.

Chapter 13

  1. Drill: Introduction toGraph_lib members: drawSimple_window,grid,Rectangle &Image objects.
  2. Define anArc which is a part of an Ellipse. Hint:fl_arc().
  3. Draw a box with rounded corners. Define a classBox, consisted of four lines and four arcs.
  4. Define classArrow that draws a line with an arrowhead.
  5. Define functionsn(),s(),e(),w(),center(),ne(),se(),sw(),nw(). Each takes aRectangle as argument and returns aPoint. These functions define "connection points" on and in the rectangle.
  6. Connection points withCircles andEllipses.
  7. Write a program that draws a class diagram depicting dependency hierarchy.
  8. Make a RGB colour chart.
  9. Create a classHexagon, where centre and distance from the centre to a corner point are the constructor arguments.
  10. Tile a part of a window using `Hexagon'; use at least six hexagons.
  11. Define a classRegular_Polugon. Use the centre and the number of sides (> 2) as a constructor arguments.
  12. Draw a 300 X 200Ellipse, a 400 - pixels - long x axis and 200 - long y axis through the centre of the ellipse.Mark the foci.Mark a point on the ellipse and not on the axis and connect it to the foci withLines.
  13. Draw aCircle. Move aMark on the circle each timeNext is pushed.
  14. Draw the RGB colour chart without the lines around the colours.
  15. Define aRight_Triangle class. Draw an octagonal shape using eight right triangles of different colour.
  16. Tile a window with small right triangles.
  17. Tile a window with small hexagons.
  18. Tile a window with small hexagons of different colour.
  19. Define a classPoly that represents a polygon. Check if points constitute a polygon.
  20. Define a classStar. One parameter should be number of points. Draw few stars with different number of points and colours.

Chapter 14

  1. Drill: main features of OOP: interface & implementation inheritance ((abstract) base - derived classes), run - time polymorphism (virtual and pure virtual functions), encapsulation & data hiding (public, protected and private).
  2. Define classesSmiley andFrowny, both derived fromCircle, with memberseyes andmouth. Next, derive classes fromSmiley andFrowny which adds an appropriate hat to each.
  3. Try to copyShape. Comment the result.
  4. Define an abstract class and then try to instantiate an object of that class. Comment the result.
  5. Define a classImmobile_Circle that can't be moved.
  6. Define aStriped_Rectangle where instead of fill the rectangle is"filled" with one-pixel-width lines. Play with line width and spacing.
  7. Define aStriped_Circle using the technique fromStriped_Rectangle.
  8. Define aStriped_Polyline using the technique fromStriped_Rectangle.
  9. Define a classOctagon to be a regular octagon. Test all its functions.
  10. DefineGroup to be a container ofShapes with suitable operations applied to the members ofGroup. UseGroup to define a checkers board where piece can be moved under program control.
  11. Define aPseudo_window with rounded corners, label, control icons, fake contents such as image, within aSimple_window.
  12. Define aBinary_tree class derived fromShape. Give the number of levels as parameter, depict nodes as circles.
  13. ModifyBinary_tree to draw its nodes using a virtual function. Derive a new class fromBinary_tree that overrides the that virtual function to use different representation for a node (e.g. a triangle).
  14. Add an operation toBinary_tree that adds text to node. Choose a way to identify a node (by a string of directions"lrlrl") for navigating left and right down a the tree (root is bothl andr).
  15. Define a classIterator with purevirtual functionnext() that returns a pointer todouble. Now deriveVector_iterator andList_iterator fromIterator so thatnext() for the first yields a pointer to the next element of avector<double> and the latter one tolist<double>. You initialize aVector_iterator withvector<double> and the first call tonext() yields a pointer to the first element, if any. If there is no next element, return0. Test both by using a functionvoid print (Iterator) to print the elements of vector and list ofdoubles.
  16. Define classController with fourvirtual functionson(),off(),set_level(int) andshow(). Derive at least two classes fromController. One should be a simple test class whereshow() prints out whether the class is seton oroff and what the currentlevel is. The second class should control the line colour ofShape; the exact meaning of of "level" is up to you.
  17. Draw a class hierarchy for thestd::exception C++ standard library.

Chapter 15

  1. Drill 1: Function graphing. Draw a coordinate system and functions.
  2. Drill 2: Class definition. Define aclass,const access members, overload extractionoperator>> and insertion operators. Check validity of class instantiation data.
  3. Implement aniterative factorial function. Compare it torecursive, comment complexity?
  4. Define a class just likeFunction, but one that stores its constructor arguments and allows reset of their value.
  5. Modify the the previous class and add new constructor argument that controls precision.
  6. Plotsin(x),cos(x), their sum and the sum of their squares on a single graph. Provide labels.
  7. Animate theLiebniz series:$1 - 1/3 + 1/5 - 1/7 + 1/9... = pi / 4$.
  8. Design and implement a bar graph with basic datastd::vector ofdouble. Each value is represented by a "bar"'s height.
  9. Modify the bar graph to allow labelling of individual bars and colour.
  10. Here is a collection of (height[cm], frequency[people]) data points: (170, 7) (175, 9) (180, 23) (185, 17) (190, 6) (195, 1). Place them in a file, read and plot them. What would be the best graphical representation? Do a bar graph.
  11. Find another data set of heights (in inches (1 inch = 2.54 cm)) and plot them with the code from the previous exercise. Scaling from the data is a key idea.
  12. Find a way of displaying a collection of labelled points.
  13. Read a data file containing mean maximum temperatures for each month of the year, for two locations and plot them together.

Chapter 16

  1. Type the line - drawing program from §16.5 to §16.7.
  2. MakeMy_window based onWindow with two buttonsnext andquit.
  3. Make a 4 x 4 Checkers board with four square buttons. When pressed, every button performs simple action: prints own coordinates, changes colour; till another button is pressed.
  4. Define class with aButton that moves to a random position when pressed, together with anImage placed on it.
  5. Make a menu with items that draws a circle, a square, an equilateral triangle, and a hexagon respectively. Make an input box for giving coordinate pair, and place the shape made by pressing a menu item at that coordinate.
  6. Make a program that draws a shape of you choice and moves it to a new point each time you click "Next". The new point should be determined by a coordinate pair read from an input stream.
  7. Make an "Analog Clock", that is, a clock with hands that move; get the time from OS library; find functions that wait for short period of time.
  8. Make an image of an airplane "fly around" in a window. Have a "start" and "stop" button.
  9. Provide a currency converter. Read the conversion rates from file on start-up. Enter amount in an input window and provide a way of selecting currencies to convert to and from (e.g. a pair of menus).
  10. Modify the calculator from Chapter 7 to get its input from input box and to return its results to output box.
  11. Provide a program where one can choose among a set of functions (e.g.sin(x),log(x)), provide parameters for those functions, and then graph them.

Chapter 17

  1. Try This: applysizeof() operator to the fundamental types and observe result. Analyse the behaviour of class constructors and destructors.
  2. Drill: operatornew and free-store allocations. Pointers, references and their properties.
  3. What is the output format of a pointer value.
  4. How many bytes are there inint,double,bool and other built-in types?
  5. Write a functionvoid to_lower(char \*s) that converts C-style string to lower case.
  6. Write a functionchar\* strdup(char\*) that copies C-style string on free store.
  7. Write a functionchar\* find(const char\* s, const char\* x), that finds first occurrence of the C-style stringx ins.
  8. Find a way to exhaust your machine's memory. Find what happens. Try usingnew or read documentation.
  9. Read individual characters, until an exclamation mark (!) is entered, fromstd::cin into an array allocated on the free store.
  10. Redo previous exercise usingstd::string instead of free store array.
  11. Write a program that determines address order inheap,stack (andstatic) memory allocation.
  12. Redo Exercise 7 (here 9) and usemalloc() -free() andrealloc() to extend the inputchar array.
  13. Complete the "list of gods" from §17.10.1 and run it.
  14. Why are there two different definitions offind() in the doubly linked list class?
  15. ModifyLink to hold a valuestruct God, with data members:std::string: name, mythology, vehicle and weapon. Write aprint_all() andadd_ordered() methods that places a new element in lexicographically right order. Make three list of Gods of different mythologies and then move them into ordered lists.

Chapter 18

  1. Constructor (default, parameter, copy and assignment) and destructor calls.
  2. Custom vector implementation, return by value and reading-only access.
  3. Drill: arrays and vectors.
  4. Write a function that copies a C-style string into free store memory and returns a pointer to it. Use dereferenceoperator *, instead of subscriptingoperator[]; and no standard library functions.
  5. Write a function that finds the first occurrence of a C-style stringx ins; without any standard library functions and with the use of the dereferenceoperator * instead of subscriptingoperator[].
  6. Write a function that compares C-style string and returns negative value if first argument lexicographically before the second, positive value otherwise and 0 of they match.
  7. Test the functions for non-zero terminated strings. Modify the functions to handle non-zero terminated strings.
  8. Write a function,cat_dot(), that concatenated two strings with a dot in between.
  9. Modifycat_dot() function to concatenate two strings, adding a separator in between, passed as third argument.
  10. Rewritecat_dot() for c-style strings as input parameters; let it return a c-string on the heap.
  11. Rewrite all the functions from chapter §18.6 to check for palindrome by making a backward copy of the string and then comparing to the original.
  12. Consider the memory layout in §17.3 (text, static, stack and heap). Write a program the shows memory addresses growth in each of the different types of memory.
  13. Look at the "array solution" to the palindrome problem and fix it to handle: long strings by, either reporting for too long strings or allowing arbitrary long strings.
  14. Look up and implement askip list. (Not an easy exercise).
  15. Implement a version of the game "Hunt the Wumpus". Make it work via the console.

Chapter 19

  1. Try this 1: Consider problems in functionresize():"Out of range error" in vector element access.
  2. Try this 2: addtry-catch blocks in functionsuspicious() at all the places where resources are released.
  3. Try this 3: modify functionreserve() to useauto_ptr; compare solution to one wherevector_base is used.Remark: impossible to implement usingauto_ptr - no pointer arithmetic supported, can't access all elements.
  4. Drill: exercises ontemplates<\>.
  5. Write a template function thataccumulates astd::vector of elements of an object of any type to which elements can be added.
  6. Write a template function that takes twostd::vectors as arguments and returns theirinner product.
  7. Write a templateclass Pair that can hold a pair of values of any type. Use this to implement a simple symbol table as the one used §7.8.
  8. Modifyclass Link from §17.9.3 to be atemplate with the type of a value as the template argument. Redo Exercise 13 Chapter 17 withLink ofGod.
  9. Define aclass Int having a single member of typeint. Define constructors, assignment,operators +,-,/,*, I/Ooperators <,operator >>.
  10. Define a templateclass Number ofT having a single member of any valid numeric type. Define constructors, assignment,operators+,-,/,\*, I/Ooperators <,operator >.
  11. Redo Exercise 2, i.e. find theinner product of two vectors of using typesNumber ofT.
  12. Implement the allocator from §19.3.6 usingmalloc() andfree(). Get thevector as defined by the end of §19.4 to work for a few simple test cases.
  13. Re-implementvector::operator() (§19.2.5) using an allocator §19.3.6 for memory management.
  14. Implement a simpleauto_ptr supporting: constructor, destructor,operator->,\*, andrelease().
  15. Design and implement acounted_ptr ofT that is a type that holds a pointer to an object of typeT and a pointer to a "use count (anint) shared by all counted pointers to the same object of typeT. The use count should hold the number of counted pointers pointing to a givenT.
  16. Design and implement a file handler that takes a string argument (file name), opens the file in the constructor and closes it in the destructor.
  17. Write a Tracer class where its constructor and destructor prints a string. Give the strings as constructor arguments. Experiment with Tracers as: local objects, global, objects allocated bynew. Add copy constructor and copy assignment and observe where copying is done.
  18. Provide a simple GUI interface output to the "Hunt the Wumpus" from Chapter 18. Take the input from an input box and display a map of the part of the cave currently known to the player in a window.
  19. Modify the previous exercise to allow the user to mark rooms on the map based on knowledge and guesses, such as"maybe bats" and"bottomless pit".
  20. Define a vector sosizeof( vector<int> )== sizeof( int * ), that is, the vector itself consists only of a pointer to a representation consisting of the elements, the number of elements, and thespace pointer.

Chapter 20

  1. Try this 1: modify the existing code and remove the ugliness.
  2. Try this 2: remove errors from the modified code.
  3. Try this 3: Write a functionvoid copy (int* f1, int* e2, int* f2) that copies the elements of an array of ints defined by[f1, e1) into another[f2: f2 + (e1- f1)). Use only iterator operations and no subscriptoperator[].
  4. Try this 4: find and remove the error in the code.
  5. Try this 5: Implementpush_front() forvector and compare it topush_back().
  6. Try this 6: Modify the functionadvance() to accept negative argument.
  7. Try this 7: For each array ofchar,vector ofchar,list ofchar, andstring, define one with the value"Hello", pass it to a function as an argument, write out the number of characters in the string passed, try to compare it to "Hello", copy the argument into another variable of the same type.
  8. Try this 8: Redo the previous Try This using containers of typeint, initialized to{ 1, 2, 3, 4, 5 }.
  9. Drill: Usestd::array,std::vector,std::list. Definecopy() andstd::find().
  10. Do all the Try This exercises.
  11. Get the "Jack and Jill" example from §20.1.2 to work. Use input from a couple of small files to test it.
  12. Look the palindrome example from §18.6; redo the Jack and Jill example from §20.1.2 using that variety of techniques.
  13. Find and fix errors in Jack and Jill in §20.3.1 by using STL techniques throughout.
  14. Define<operator and>operator forstd::vector.
  15. Write find and replace function forclass Document based on §20.6.2.
  16. Find the lexicographically last string in an unsortedstd::vector<std::string>.
  17. Define a function that counts the number of characters inDocument.
  18. Define a function that counts the number of words inDocument, where word is defined as:"white space separated sequence of characters" or"sequence of alphabetic characters".
  19. Define a function that counts the number of words inDocument, where the white space string is defined via function's argument.
  20. Give a liststd::list ofint as a (by - reference) parameter, make astd::vectordouble and copy the elements of the list into it. Verify the copy was correct and complete. Print the elements sorted in increasing value.
  21. Complete the definition ofList from §20.4.1 - 2 and gethigh() example to run. Allocate aList to represent one past the end.
  22. Modify the solution to the previous exercise to use0 to represent the (non- existent) one-past-the-endLink (list<Elem> ::end()); that way the size of empty list is equal to the size of simple pointer.
  23. Define a singly-linked list,slist, in the style ofstd::list. Which operations fromList should be kept?
  24. Define apvector to be likevector of pointers except that it contains pointer to objects and its destructor deletes each object.
  25. Define anownership_vector that holds pointers to objects likepvector, but provides a mechanism for the user to decide which objects are owned by the vector (i.e., which objects aredeleted by the destructor).
  26. Define a range-checked iterator forvector (a random-access iterator).
  27. Define a range-checked iterator forlist (a bidirectional iterator).
  28. Comparevector andlist. GenerateN randomint numbers in the range[0, N). As eachint is generated. insert it into avector ofint. Keep thevector sorted; that is, a value is inserted after every previous value that is less than or equal to the new value and before every value that is larger than the new value; do the same for thelist. Explain result. (§26.6.1 explains how to time a program.)

Chapter 21

  1. Try This 1: Write, test the functionsfind() and construct an argument for their being equivalent.
  2. Try This 2: Why using implicit parameters could lead to obscure errors. List three examples where they should be avoided.
  3. Try This 3: Define astd::vector ofRecord, initialize it with four Records of your choice, and compute their total price using the function in §21.5.2.
  4. Try This 4: Write the example from §21.6.3 and get it to run.
  5. Try This 5: Write a small program using#include <unordered_map>.
  6. Try This 6: Get the program from §21.7.2 to run and test with small files of few hundred words. Try (the not recommended) guessing of the input size (potentially leading to buffer overflow).
  7. Drill 1:algorithms withstd::vector andstd::list.
  8. Drill 2:algorithms withstd::map.
  9. Drill 3:algorithms withstd::vector<int> andstd::vector<double>.
  10. Do all Try this exercises (in case you haven't).
  11. Find a reliable STL documentation and list every standard library algorithm.
  12. Implementcount() yourself. Test it.
  13. Implementcount_if() yourself. Test it.
  14. Reimplementcount() andcount_if() as if there is noend() iterator.
  15. Redo §21.6.5 but withstd::set<Fruit*> instead. Provide a comparison operationFruit_comparison, forstd::set<Fruit*, Fruit_comparison>.
  16. Implement abinary_search() function forstd::vector andstd::list. Test it. How much do they resemble each other?
  17. Take the word frequency example from §21.6.1 and and modify it to to output its lines in order of frequency.
  18. Define anOrder class with (customer)name,address,data andvector ofPurchase members.Purchase is a class with (product)name,unit prince, andcount members. Define a mechanism for reading and writing to and from file. Define a mechanism for printing orders. Create a file of at least 10 orders, read it into avector ofOrder, sort it by name (of customer), and write it back to file. Create another file of at least tenOrders, of which about the third are the same as in the first file, read into alist ofOrder, sort by address of customer and write back out to file. Merge the two files into third usingstd::merge();
  19. Provide a GUI interface for enteringOrders into files.
  20. Provide a GUI interface for querying a file ofOrders; e.g., "Find all orders from Joe," "Find the total value of orders in file Hardware," and "List all orders in file Clothing."
  21. "Clean up" a text file for use in a word query program; that is, replace punctuation with white space, put words into lower case, replace"don't" with"do not" (etc.), and remove plurals (e.g., ships becomes ship).
  22. Using the output from the previous exercise to answer questions such as:"How many occurrences of ship are there in a file?","Which word occurs most frequently?","Which is the longest word in the file?","Which is the shortest?","List all words starting with s.","List all four-letter words."
  23. Provide a GUI for the previous exercise.

Chapter 22

  1. Define programming.
  2. Define programming language.
  3. Which of the chapter vignettes were written by a scientist? Write a paragraph with the contribution of each scientist.
  4. Which of the chapter vignettes were written not by a scientist?
  5. Write a"Hello, World!" program in each of the languages mentioned in this chapter.
  6. For each language mentioned in this chapter, look at a popular textbook and see what is used as the first complete program. Write that program in all of the other languages. Warning: This could easily be a 100 - program project.
  7. Make a list of five modern languages that you think ought to be covered and write a page and a half - along the lines of the languages sections in this chapter.
  8. What is C++ used for and why? Write a 10- to 20- page report.
  9. What is C used for and why? Write a 10- to 20-page report.
  10. Pick one language (not C or C++) and write a 10- to 20-page description of its origins, aims, and facilities. Give plenty of concrete examples. Who uses it and for what?
  11. Who currently holds the Lucasian Chair in Cambridge?
  12. Of the language designers mentioned in this chapter, who has a degree in mathematics? Who does not?
  13. Of the language designers mentioned in this chapter, who has a Ph.D.? In which field? Who does not have a Ph.D.?
  14. Of the language designers mentioned in this chapter, who has received tlle Turing Award? What is that? Find the actual Turing Award citations for the winners mentioned here.
  15. Write a program that, given a file of (name,year) pairs, such as (Algol,1960) and (C,1974), graphs the names on a timeline.
  16. Modify the program from the previous exercise so that it reads a file of (name,year,(ancestors)) tuples, such as (Fortran,19S6,()), (Algol,1960,(Fortran), and (C++,198S,(C,Simula)), and graphs them on a timeline with arrows from ancestors to descendants. Use this program to draw improved versions of the diagrams in §22.2.2 and §22.2.7.

Chapter 23

  1. Try this 1: What would be a better error handling? Modify Mail_file's constructor to handle likely formatting errors related to the use of "----" - (end of message indicator).
  2. Try this 2: Write a brief explanation of the new terms used in the current section of the chapter.
  3. Try this 3: Get the program from §23.8.7 to run and use it to try out some patterns, such as:abc,x.*x,(.*),\([^)]*\),\w+ \w+( Jr\.).
  4. Drill: Find out ifregex is shipped as part of your standard library. Try:std::regex andtr1::regex. Get the program from §23.7.7 to run. Install boost library; set project options; and include needed headers. Use the program to test the pattern from §23.7.
  5. Exercise 1: Get the Mail_file example to run with file of your creation. Be sure to test with error-causing messages, such as: ones with two addresses, multiple messages with same addresses or same subject, and empty message. Test with file containing something that is not a message, such as a file containing only ....
  6. Add amultimap and have it hold subjects. Let the program take an input string from the keyboard and print out every message with that string as its subject.
  7. Modify the email example from §23.4 to use regular expressions to find the subject and sender.
  8. Apply the previous program on real list of emails and extract the lines containing the subject.
  9. Comparestd::multimap againststd::unordered_multimap, having in mind that the latter doesn't take advantage of ordering.
  10. Write a program that finds dates in a file and displays the line containing the date and its number. Start with regular expression for simple formats like:12/24/2017. Add more formats later.
  11. Write a program that finds redit card numbers in a file and displays the line containing the date and its number.
  12. Write a program that finds a pattern in a file and displays the line containing the pattern and its number.
  13. Usingeof() (§B.7.2), it is possible to determine which line of a table is the last. Use that to (try to) simplify the table-checking program from §23.9. Be sure to test your program with files that end with empty lines after the table and with files that don't end with a newline at all.
  14. Modify the table-checking program from §23.9 to write a new table where the rows with the same initial digit are merged.
  15. Modify the table-checking program from §23.9 to see if the number of students is increasing or decreasing over the years in question.
  16. Write a program, based on the program that finds lines containing dates, that finds all dates and reformats them to the ISOyyyy/mm/dd format. The program should take an input file and produce an output file that is identical to the input file except for the changed date formatting.
  17. Does dot(.) match'\n'? Write a program to find out.
  18. Write a program similar to the one in §23.8.7, have it read a file into memory (representing a line break with the newline character,'\n'), so that you can experiment with patterns spanning line breaks. Test it and document a dozen test patterns.
  19. Describe a pattern that cannot be expressed as a regular expression.
  20. Prove that the pattern found in the previous exercise really isn't a regular expression.

Chapter 24

  1. Try this 1: sum a the fraction1/nn times and observe the result. Is it1? Rounding Error.
  2. Try this 2: Run the examples from §24.2 showing truncation, overflow and underflow examples due to intertype assignments, implicit conversion and algebraic calculations.
  3. Drill 1: Print the size of achar, ashort, anint, along, afloat, adouble, anint*, and adouble*. (usesizeof, notlimits).
  4. Drill 2: Print out the size as reported bysizeof of Matrix ofint:a(10), Matrix of int:b(10), Matrix of double:c(10), 2D Matrix of int:d(10,10), 3D Matrix of int:e(10, 10, 10).
  5. Drill 3: Print out the elements of the matrices from the previous exercise.
  6. Drill 4: Write a program that takes ints from d n and outputs thesqrt() of eachint, or "no square root" ifsqrt(x) is illegal forsome x (i.e., check yoursqrt() return values).
  7. Drill 5: Read ten floating-point values from input and put them into aMatrix ofdouble. Matrix has nopush_back() so be careful to handle an attempt to enter a wrong number of doubles. Print out theMatrix.
  8. Drill 6: Compute a multiplication table for[O, n) x [O,m) and represent it as a 2D Matrix. Taken andm fromstd::cin and print out the table nicely (assume thatm is small enough that the results fit on a line).
  9. Drill 7: Read tencomplex ofdoubles fromstd::cin and put them into aMatrix. Calculate and output the sum of the tencomplex numbers.
  10. Drill 8: Read sixints into a2D Matrix ofint,m(2, 3) and print them out.
  11. The function argumentsf fora.apply(f) andapply(f,a) are different. Write adouble() function for each and use each to double the elements of an array{ 1, 2, 3, 4, 5 }. Define a singledouble() function that can be used for botha.apply(double) andapply(double, a). Explain why it could be a bad idea to write every function to be used byapply() that way.
  12. Do, the previous, Exercise 1 again, but withfunction objects, rather than functions.
  13. Write anapply(f,a) that can takes avoid f(T&), aT f(const T&), and their function object equivalents. Hint:Boost::bind.
  14. Get the Gaussian elimination program to work; that is, complete it, get it to compile, and test it with a simple example.
  15. Try the Gaussian elimination program withA={ {O 1} {1 O} } andb={ 5 6 } and watch it fail. Then, tryelim_with_partiat_pivot().
  16. In the Gaussian elimination example, replace the vector operationsdot_product() andscale_and_add() with loops. Test, and comment on the clarity of the code.
  17. Rewrite the Gaussian elimination program without using the Matrix library; that is, use built-in arrays or vectors instead of Matrices.
  18. Animate the Gaussian Elimination.
  19. Rewrite the non-memberapply() functions to return aMatrix of the return type of the function applied that is,apply(f, a) should return aMatrix of typeR whereR is the return type off. Warning: The solution requires information about templates not available in this book.
  20. How random is yourrand()? Write a program that takes two integersn andd as inputs and callsrandint(n)d times, recording the result. Output the number of draws for each of[0 : n) and "eyeball" how similar tile counts are. Try with low values forn and with low values ford to see if drawing only a few random numbers causes obvious biases.
  21. Write aswap_columns() to matchswap_rows() from §24.S.3. Obviously, to do that you have to read and understand some of the existingMatrix library code. Don't worry too much about efficiency: it is not possible to getswap_columns() to run as fast asswap_rows().
  22. Implement:Matrix operator multiplication (2DMatrix&, 1DMatrix&);, i.e. tensor-vector dot product andMatrix operator+ (Matrix&, Matrix&); for randomly multidimensional matrices.

Chapter 25

  1. Try This 1: Replace333 in the example with10 and run the example again. What result would you expect? What result did you get?
  2. Тry This 2: Before reading further, try to see how many errors you can find inf() in §25.4.3. Specifically, which of the calls ofpoor() could cause the program to crash?
  3. Try This 3: Get the bits example to work and try out a few values to develop a feel for binary and hexadecimal representations. If you get confused about the representation of negative values, just try again after reading §25.5.3.
  4. Try This 4: Inspect the loop in §25.5.3 with signedchar as loop variable andunsigned char as termination variable. Why it's infinite?
  5. Try This 5: Draw out the bit patterns on a piece or paper. Using paper, then figure out what the answer would be forsi = 128 in §25.5.3. Then run the program to see if your machine agrees.
  6. Drill 1: Bit shifting and multiplication.
  7. Drill 2: Unsigned short Bit manipulations.
  8. Exercise 1: Do Try This Exercise.
  9. Hexspeak.
  10. Integer bit patterns.
  11. Add the bitwise logical operators&,|,^ , and~ to the calculator from Chapter 7.
  12. Write an infinite loop. Execute it.
  13. Write an infinite loop that is hard to recognize as an infinite loop. A loop that isn't really infinite because it terminates after completely consuming some resource is acceptable.
  14. Write out the hexadecimal values from0 to400; and from-200 to200.
  15. Write out the numerical values of each character on your keyboard.
  16. Without using any standard headers (such aslimits or documentation, compute the number of bits in anint and determine whetherchar issigned orunsigned on your implementation.
  17. Look at the bitfield example from §25.5.5. Write an example that initializes aPPN, then reads and prints each field value, then changes each field value (by assigning the field), and prints the result. Repeat this exercise, but store thePPN information in a 32-bitunsigned integer and use bit manipulation operators (§25.5.4) to access the bits in the word.
  18. Redo previous exercise usingbitset.
  19. Write out the clear text of the example from §25.5.6.
  20. Implement a simplevector that can hold at mostN elements allocated from a pool. Test it forN == 1000 andinteger elements.
  21. Measure the time it takes to de / allocate10000 objects of random sizes in[10000:0) - byte range. Do this twice: once deallocate in reverse order and once deallocate in random order.
  22. Formulate 20 coding style rules (don't just copy those in §25.6). Apply them to a program of more than 300 lines that you recently wrote.
  23. Proof thatArray_ref handles inheritance correctly by trying to get aRectangle\* intostd::vector<Circle\*> usingArray_ref<Shape\*>, without using casts or other operations involving undefined behaviour.

Chapter 26

  1. Implement aBinary Search algorithm by yourself. How do you know it is correct?
  2. Drill 1: Implement the input operator forTest from §26.3.2.2.
  3. Drill 2: Complete a file of tests for the sequences from §26.3: empty sequence, single element, odd and even number, equal elements, different elements at end.
  4. Drill 3: Based on §26.3.2.3, complete a program that generates (ordered): a very large sequence, ten sequences with random number of elements, ten sequences with elements:0,1,2,...,9 random elements.
  5. Drill 4: Repeat these tests for sequences of strings, such as:{ Bohr Darwin Einstein Lavoisier Newton Turing }.
  6. Exercise 1: Run your binary search algorithm from §26.1 wilt the tests presented in §26.3.2.1.
  7. Modify the testing ofbinary_search() to deal with arbitrary element types. Then, test it withstd::string sequences andfloat sequences.
  8. Repeat the exercise in §26.2.1 with the version ofbinary_search that takes a comparison criterion. Make a list of new opportunities for errors introduced by that extra argument.
  9. Devise a format for test data so that you can define a sequence once and run several tests against.
  10. Add a test to the set ofbinary_search tests to try to catch the (unlikely) error of abinary_search modifying the sequence.
  11. Modify the calculator fromChapter 7 minimally to let it take input from a file and produce output to a file (or use your operating system's facilities for redirecting I/O ). Then devise a reasonably comprehensive test for it.
  12. Test the "simple text editor" from §20.6.
  13. Add a text-based interface to the graphics interface library from Chapters 12 - 15. For example, the string: "Circle(Point(O, 1), 15)" should generate a callCircle(Point(O, 1), 15). Use this text interface to make a "kid 's drawing" of a two-dimensional house with a roof, two windows, and a door.
  14. Add a text-based output format for the graphics interface library. For example, when a callCircle(Point(0,1),15) is executed, a string like: "Circle(Point(0,1),15)" should be produced on an output stream.
  15. Use the text-based interface from Exercise 9 to write a better test for the graphical interface library.
  16. Time the sum example from §26.6 withm being square matrices with dimensions100,10.000,1.000.000, and10.000.000. Use random element values in the range[-10: 10). Rewrite the calculation ofv to use a more efficient (not O(n^2)) algorithm and compare the timings.
  17. Write a program that generates random floating-point numbers and sorts them usingstd::sort. Measure the time used to sort500,000 doubles and5,000,000 doubles.
  18. Write a program that generates random length, within[0,100),std::strings and sorts them usingstd::sort. Measure the time used to sort500,000 and5,000,000 strings.
  19. Repeat the previous exercise, except using astd::map rather than astd::vector so that we don't need to sort.

Chapter 27

  1. Try This 1: Testcat(). Why2? We left a beginner's performance error incat(); find it and remove it. We "forgot" to comment our code. Add comments suitable for someone who can be assumed to know the standard C - string functions.
  2. Is this implementation ofstrcpy() correct? Explain why.
  3. Rewrite the intrusive list example in C++, showing how to make it shorter and easier to use without making the code slower or the objects bigger.
  4. Drill 1: Write a"Hello, World!" program in C, compile it, and run it.
  5. Define two variables holding"Hello" and"World!" respectively; concatenate them with a space in between; and output them asHello, World!.
  6. Define a C function that takes achar* parameterp and anint parameterx and prints out their values in this format:p is"foo" andx is7. Call it with a few argument pairs.
  7. Exercise 1: Implement versions ofstrlen(),strcmp(), andstrcpy().
  8. Complete the intrusive list example in §27.9 and test it using every function.
  9. "Pretty up" the intrusive list example in §27.9 as best you can to make it convenient to use. Do catch / handle as many error's as you can. It is fair game to change the details of thestruct definitions, to use macros, whatever.
  10. If you didn't already, write a C++ version of the intrusive list example in §27.9 and test it using every function.
  11. Compare the results of Exercises 3 and 4.
  12. Change the representation ofLink andList from §27.9 without changing the user interface provided by the functions. AllocateLinks in an array ofLinks and have the members:first,last,prev, andnext beints (indices into the array).
  13. What are the advantages and disadvantages of intrusive containers compared to C++ standard (non-intrusive) containers? Make lists of pros and cons.
  14. What is the lexicographical order on your machine? Write out every character on your keyboard together with its integer value; then, write the characters out in the order determined by their integer value.
  15. Using only C facilities, including the C standard library, read a sequence of words from stdin and write them to stdout in lexicographical order. Hint: The C sort function is calledqsort(); look it up somewhere. Alternatively, insert the words into an ordered list as you read them. There is no C standard library list.
  16. Make a list of C language features adopted from C++ or C with Classes (§27.1).
  17. Make a list of C language features not adopted by C++.
  18. Implement a (C-style string,int) lookup table with operations such asfind (struct table*, const char*),insert (struct table*, const char*, int), andremove (struct table*, const char*). The representation of the table could be an array of a struct pair or a pair of arrays (const char* [] andint*); you choose. Also choose return types for your functions. Document your design decisions.
  19. Write a program that does the equivalent ofstring s;cin >> s; in C; that is, define an input operation that reads an arbitrarily long sequence of white space - terminated characters into a zero - terminated array ofchars.
  20. Write a function that takes an array ofints as its input and finds the smallest and the largest elements; It should also compute the median and mean. Use astruct holding the results as the return value.
  21. Simulate single inheritance in C. Let each "base class" contain a pointer to an array of pointers to functions (to simulate virtual functions as free standing functions taking a pointer to a "base class" object as their first argument); see §27.2.3. Implement "derivation" by making the "base class" the type of the first member of the derived class. For each class, initialize the array of "virtual functions" appropriately. To test the ideas, implement a version of "the old Shape example" with the base and deriveddraw() just printing out the name of their class. Use only language features and library facilities available in standard C.
  22. Use macros to obscure (simplify the notation for) the implementation in the previous exercise.

===

Additional dependencies:

For the first few chapters:

http://www.stroustrup.com/Programming/std_lib_facilities.h

For chapters 12 - 15, in some exercises in chapters 21, 22, 26:

http://www.stroustrup.com/Programming/FLTK/

For chapter 24:

http://www.stroustrup.com/Programming/Matrix/

Files structure and code style:

Each file starts with:

/*    TITLE          [brief_title]                [file_name.extension]    Book name and author.    COMMENT        Objective: [exercise intent]            Input: [expected]           Output: [expected]           Author: [name]             Date: [date of last modification]*/

For the sake of claritybraces ,{ }, are on a new line:

int main() {    // Code        // indentation            // is                // 4                    // spaces.        }

Names ofvariables andfunctions start with lower case and contain upper case or underscore"_", in case of complex names;classes andnamespaces start with upper case. Example:

namespace MyExample {    int var;    int func (int par);        int res_var;        class ObjectOriented    {        };}

File organization:

1.Main (Execution) files,FileName.cpp, contain the included compiler libraries
and custom libraries, followed by themain() function;
Global variables are avoided.

2.Header files,FileName.h contain guards using the file name in upper case:

#ifnded FILE_NAME_H#define FILE_NAME_H// declarations#include "FileNameDef.cpp"#endif

3.Implementation filesFileNameDef.cpp contain class/function implementations,
separated either by:

----------------------------

or

===========================

with comments before the body of definition:

/*    Function:    Use:        Description*/

Files naming convention:

Chapter[number]TryThis[number].cpp

Chapter[number]Drill[number].cpp

Chapter[number]Exercise[number].cpp

Chapter[number]Exercise[number].h

Chapter[number]Exercise[number]Def.cpp


OS: Windows 7, Windows 10
IDE: Visual Studio 2010, CodeBlocks


MIT License

Copyright (c) 2017 Chris B. Kirov

Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.

About

Solutions to the Exercises from ""Programming Principles and Practice Using C++"" by Bjarne Stroustrup

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

[8]ページ先頭

©2009-2025 Movatter.jp