Exercises from
"Programming Principles and Practice Using C++"
- Compile a list of daily activities involving the use of computers.
- Pick a favourite profession and the activities within it involving the use of computers.
- Swap the lists from Ex 1 and Ex 2 with a friend and compare results.
- List of activities not possible without computers.
- List of programs that you have used.
- List of activities not involving computers.
- Five tasks for which computers will be used in the future.
- Why do you like to be a programmer? (
$100 < words < 500$ ) - What other role in computer industry do you like to play?
- Do you think computers will ever be developed to be conscious, thinking, capable of competing with humans?
- List of characteristics that good programmers share.
- Identify five applications for computer programs mentioned in the chapter and one that you want to participate in.
- How much memory would it take to store: this page, text, Shakespeare's work. (1 byte == 1 character; Estimate 20% precision)
- How much memory (main, disk) does your computer have?
- Print
"Hello, programming!\nHere we go!"
. - Write pseudo code (instructions) directing "the computer" upstairs to the bathroom.
- Write pseudo code (instructions) directing "the computer" from your house/dorm to work/university.
- Write instructions for a food cooking recipe.
- Write definition of each of the new terms covered in the first chapter.
- Do all Try This examples in the chapter.
- Miles to kilometers converter.
- Check compiler response to illegal variable names (identifiers).
- Define and read two
int
s. Find and print their min, max, sum, difference, product and ratio. - Redo the Exercise 4 with floating point number variables
double
. - Read three
int
s and list them in increasing order. - Redo Exercise 6 with
string
s. - Check if
int
is odd or even. - Read an
int
as digit / name and print it as name / digit. - Read an operation (
+, -, *, /
) and two (double
) values and print the result. (Useif
statements). - Read
pennies, nickels, dimes, quarters
andhalf dollars
and print total sum ofcents
.
- Do all Try This examples in the chapter.
- Find median (element in the middle of the sorted set). Modify
4.6.2
- Read
double
values and store them into avector
. Find total sum, mean of all elements, min and max. - Write a number guessing game. (manual Binary seach using
if
statements). - Implement a simple calculator with few operations
$(+, -, *, /, %)$ . - Store the names of the digits [0, 9] in a
vector
and use it to convert digit to its name. - Modify Exercise 5 to accept either single digit or its name.
- Calculate Exponential growth after
n
turns. - Largest value held in
int
ordouble
, overflow. - Implement a game "Rock, Paper, Scissors.". (use
switch
statements) - Find prime numbers within
$[1, 100]$ . (Usevector
that holds current previous primes.) - Find prime numbers within
$[min, max]$ . - Implement Sieve of Eratosthenes within
$[1,100]$ . - Modify Exercise 13 to interval
$[min, max]$ . - Find first
n
primes. - Find the mode of a sequence of positive
int
s. - Find min, max and mode of sequence of
string
s. - Solve the quadratic equation with coefficients
a
,b
andc
. - Read
name
andvalue
pairs. Check name uniqueness. - Modify Exercise 19, so that when you type
name
it prints itsvalue
. - Modify Exercise 19, so that when you type an
int
value it prints the names with that score.
- Do all Try This examples in the chapter.
- Debug existing Celsius to Kelvin converter.
- Choose appropriate
min
value and modify Ex. 2. - Handle the errors within
ctok()
. - Write a Kelvin to Celsius converter.
- Write a Celsius
$<=>$ Fahrenheit converter. (Estimate result.) - Solve the quadratic equation,
throw
an exception if discriminant< 0
. - Read
int
s (quit with|
), store them in avector
and prompt the user to sumn
of them. - Modify Ex. 8 and display error if result can't be stored in
int
. - Redo Ex. 8 with values of type
double
. Calculate the differences of adjacent elements. - Print the first
n
Fibonacci numbers. Find largest Fibonacci stored inint
. - Implement "Bulls and Cows".
- Redo Ex. 12, but let each time the numbers be random. (Use
rand()
andsrand()
) - Read
(day-of-the-week, value)
pairs and store each day in avector<int>
. Print each day and its values.
- Do all Try This examples in the chapter.
- Modify the calculator to evaluate expressions containing
$(,)$ and${,}$ . - Add factorial operator
!
. - Rework Ex. 19 Ch. 4 using a
class Name_value
. - Expand the English Grammar from 6.4.1 to include
the
. - Write a program that checks if sentence is correct according to the English Grammar.
- Write a Grammar for Logical Epxressions.
- Redo "Bulls and Cows" from Ex. 12 Ch. 5, to use four letters instead of four digits.
- Write a program that reads digits and composes them into integers.
- Calculate permutations P(a, b) and combinations C(a, b).
- Allow underscore
_
in the names of the user defined variable in the calculator. - Allow used defined variable value reassignment, by introducing an assignment
operator=
. - Allow the definition of
const
variables. - Define
class Symbol_table
and rewrite the calculator to use it. - Print result at newline
\n
. - Provide help function in the calculator.
- Change help and quit commands.
- Fix the calculator grammar and add comments (document the code).
- Define a
class Table
and rewrite the calculator to use it. - Suggest three improvements and implement one.
- Modify the calculator to operate on
int
only. - Discuss the possible source of problems of introduction of assignment
operator=
. - Revisit two programs from Ch. 4 and Ch. 5, clean and comment them.
- Modify the calculator to make the input stream an explicit parameter. Give
Token_stream
constructor aistream&
parameter. - Write a function
print()
that prints avector
ofint
s; Include astring
parameter label. - Find
n
Fibonacci numbers and store them in avector
. Use functionprint()
from Ex. 2 to print them. - Find the largest Fibonacci number stored in
int
. - Write a function that reverses the
int
elements of avector
. - Redo Ex. 5 using
string
s. - Read five
names
and fiveages
. Sort thenames
and match theages
. Print the result. - Implement a simple function
randint()
.(See Knuth, The Art of Computer Programming, Volume 2) - Write a function
rand_in_range(int a, int b)
that generates a pseudo-random number within$[a, b)$ , usingrandint()
. - Write a function that calculates the sum of the products of the elements of two
vector
s. (Allow one vector with smaller size). - Write a function
maxv()
that returns the largest element of a vector argument. - Find min, max, mean and median of vector arguments. Return the result using
struct
or by passing by reference. - Improve
print_until_s()
from 8.5.2. Test it. Write a functionprint_until_ss()
that prints until the second occurrence of its argumentquit
. - Write a function that takes a
vector<string>
argument and returnsvector<int>
containing the number of character in eachstring
. Also find longest and shortest, lexicographically first and laststring
s. - Can we declare a non-reference function argument
const
? Why would we? Test it.
- List sets of plausible operations for the examples of real-world objects in §9.1 (such as toaster).
- Design and implement a
Name_pairs
, holding (string name, double age
). Providesort()
operation. - Replace
Name_pair::print()
with a (global)operator<<
and define==
and!=
forName_pairs
. - Indent the code from §8.4.
- Implement a
class 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. - Add operators
==
,<<
for theclass Book
. - Create an
enum
type for theclass Book
calledGenre
. Have the types befiction
,nonfiction
,periodical
,biography
,children
. - Create a
class Patron
for tlle library. The class will have auser's name
,library card number
, andlibrary fees
(if owed). Create appropriate member functions. - Create a
class Library
. Include vectors ofBooks
andPatrons
. Include astruct
calledTransaction
. Have it include aBook
, aPatron
, and aDate
. Create appropriate member functions. - Implement
leapyear()
from §9.8. - Design and implement a set of useful helper function for the
class Date
such asnext_workday()
andweek_of_year()
. - Change the representation of a
Date
to be the number of days since January I, 1970 (known as day 0), represented as along
, and reimplement the functions from §9.8. - Design and implement a rational number
class Rational
. - Design and implement a
class Money
for calculations involvingdollars
andcents
where arithmetic has to be accurate to the lastcent
using the 4/5 rounding rule. - Refine the
class Money
by adding acurrency
. Provide a conversion table. - Give an example of a calculation where a
Rational
gives a mathematically better result thanMoney
. - Give an example of a calculation where a
Rational
gives a mathematically better result thandouble
.
- Sum of all the numbers in a file of whites space-separated integers.
- Creates a file of data in the form of the temperature
Reading
type defined in §10.5. Fill the file with at least 50 temperature readings. - Create a program that reads the data created in Exercise 2 into a
vector
and then calculates the mean and median of the temperatures in your data set. - Modify Exercise 2 to include temperature unit suffix
C
- Celsius orF
- Fahrenheit. Modify the function from Exercise 3 to firstly convert the temperature in Fahrenheit before calculating the statistics. - Write the function
prin_year()
mentioned in §1O.11.2. - Define a
Roman_int
class for holding Roman numerals (as ints) with aoperator<<
and>>
. ProvideRoman_int
with anas_int()
member. - Make a version of the calculator from Chapter 7 that accepts Roman numerals.
- Write a program that accepts two file names and produces a new file that concatenates the two files.
- Write a program that takes two files containing sorted white space-separated words and merges them, preserving the order.
- Add a command
from x
to the calculator from Chapter 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. - Write a program that produces the sum of all the white space-separated integers in a text file.
- Write a program that given a file name and a word outputs each line that contains that word together with the line number.
- Read a file, convert to lower case and write to another file.
- Remove all the vowels from a text file.
- 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. - Read a string and classify each of its characters, e.g.
isalpha()
,isspace()
, etc. - Replace punctuation with white space.
- Modify Ex. 5 to replace
don't
withdo not
andcan't
withcannot
; to leave hyphens in between words intact. - Use the knowledge from the previous exercises to create a dictionary from a multi-page text.
- Read and write a binary file.
- Write a function that accepts a string and returns a vector holding all the white space separated sub-strings of the argument.
- Expand Ex. 9 to include sub-string separation at any character passed as an additional argument.
- Reverse the order of characters in a text file.
- Reverse the order of words (white space separated) in a text file.
- Perform character classification on the contents of a text file.
- 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.
- Read a file containing integers, sort, count write the result in a table in another file.
- Drill: Introduction to reduced GUI based on FLTK: include needed libraries, create
Simple_window
. - Create a rectangle using class
Rectangle
and classPolygon
, use different colours. - Draw a
Rectangle
and place aText
object inside it. - DraW your initials in different colours.
- Draw a Checkers board, with white and red squares.
- Draw a red 1/4-inch frame around a rectangle that is 3/4 the height and 2/4 the width of the screen.
- Draw a
Shape
not matching the size of the window andWindow
not matching the size of the of the screen. - Draw a picture of a house.
- Draw the Olympic five rings.
- Display an image and manipulate it.
- Draw the file diagram of Chapter 12.8, describing the hierarchy of source code dependencies.
- Draw a series of polygons, one inside the other.
- Draw a "star-like" pattern by connecting points of super-ellipse.
- Draw super-ellipses of multiple colours.
- Drill: Introduction to
Graph_lib
members: drawSimple_window
,grid
,Rectangle
&Image
objects. - Define an
Arc
which is a part of an Ellipse. Hint:fl_arc()
. - Draw a box with rounded corners. Define a class
Box
, consisted of four lines and four arcs. - Define class
Arrow
that draws a line with an arrowhead. - Define functions
n()
,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. - Connection points with
Circles
andEllipses
. - Write a program that draws a class diagram depicting dependency hierarchy.
- Make a RGB colour chart.
- Create a class
Hexagon
, where centre and distance from the centre to a corner point are the constructor arguments. - Tile a part of a window using `Hexagon'; use at least six hexagons.
- Define a class
Regular_Polugon
. Use the centre and the number of sides (> 2) as a constructor arguments. - Draw a 300 X 200
Ellipse
, 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
. - Draw a
Circle
. Move aMark
on the circle each time Next is pushed. - Draw the RGB colour chart without the lines around the colours.
- Define a
Right_Triangle
class. Draw an octagonal shape using eight right triangles of different colour. - Tile a window with small right triangles.
- Tile a window with small hexagons.
- Tile a window with small hexagons of different colour.
- Define a class
Poly
that represents a polygon. Check if points constitute a polygon. - Define a class
Star
. One parameter should be number of points. Draw few stars with different number of points and colours.
- 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).
- Define classes
Smiley
andFrowny
, both derived fromCircle
, with memberseyes
andmouth
. Next, derive classes fromSmiley
andFrowny
which adds an appropriate hat to each. - Try to copy
Shape
. Comment the result. - Define an abstract class and then try to instantiate an object of that class. Comment the result.
- Define a class
Immobile_Circle
that can't be moved. - Define a
Striped_Rectangle
where instead of fill the rectangle is "filled" with one-pixel-width lines. Play with line width and spacing. - Define a
Striped_Circle
using the technique fromStriped_Rectangle
. - Define a
Striped_Polyline
using the technique fromStriped_Rectangle
. - Define a class
Octagon
to be a regular octagon. Test all its functions. - Define
Group
to be a container ofShape
s with suitable operations applied to the members ofGroup
. UseGroup
to define a checkers board where piece can be moved under program control. - Define a
Pseudo_window
with rounded corners, label, control icons, fake contents such as image, within aSimple_window
. - Define a
Binary_tree
class derived fromShape
. Give the number of levels as parameter, depict nodes as circles. - Modify
Binary_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). - Add an operation to
Binary_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
). - Define a class
Iterator
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 ofdouble
s. - Define class
Controller
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. - Draw a class hierarchy for the
std::exception
C++ standard library.
- Drill 1: Function graphing. Draw a coordinate system and functions.
- Drill 2: Class definition. Define a
class
,const
access members, overload extractionoperator>>
and insertion operators. Check validity of class instantiation data. - Implement an iterative factorial function. Compare it to recursive, comment complexity?
- Define a class just like
Function
, but one that stores its constructor arguments and allows reset of their value. - Modify the the previous class and add new constructor argument that controls precision.
- Plot
sin(x)
,cos(x)
, their sum and the sum of their squares on a single graph. Provide labels. - Animate the Liebniz series:
$1 - 1/3 + 1/5 - 1/7 + 1/9... = pi / 4$ . - Design and implement a bar graph with basic data
std::vector
ofdouble
. Each value is represented by a "bar"'s height. - Modify the bar graph to allow labelling of individual bars and colour.
- 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.
- 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.
- Find a way of displaying a collection of labelled points.
- Read a data file containing mean maximum temperatures for each month of the year, for two locations and plot them together.
- Type the line - drawing program from §16.5 to §16.7.
- Make
My_window
based onWindow
with two buttonsnext
andquit
. - 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.
- Define class with a
Button
that moves to a random position when pressed, together with anImage
placed on it. - 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.
- 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.
- 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.
- Make an image of an airplane "fly around" in a window. Have a "start" and "stop" button.
- 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).
- Modify the calculator from Chapter 7 to get its input from input box and to return its results to output box.
- 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.
- Try This: apply
sizeof()
operator to the fundamental types and observe result. Analyse the behaviour of class constructors and destructors. - Drill: operator
new
and free-store allocations. Pointers, references and their properties. - What is the output format of a pointer value.
- How many bytes are there in
int
,double
,bool
and other built-in types? - Write a function
void to_lower(char \*s)
that converts C-style string to lower case. - Write a function
char\* strdup(char\*)
that copies C-style string on free store. - Write a function
char\* find(const char\* s, const char\* x)
, that finds first occurrence of the C-style stringx
ins
. - Find a way to exhaust your machine's memory. Find what happens. Try using
new
or read documentation. - Read individual characters, until an exclamation mark (!) is entered, from
std::cin
into an array allocated on the free store. - Redo previous exercise using
std::string
instead of free store array. - Write a program that determines address order in heap, stack (and static) memory allocation.
- Redo Exercise 7 (here 9) and use
malloc()
-free()
andrealloc()
to extend the inputchar
array. - Complete the "list of gods" from §17.10.1 and run it.
- Why are there two different definitions of
find()
in the doubly linked list class? - Modify
Link
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.
- Constructor (default, parameter, copy and assignment) and destructor calls.
- Custom vector implementation, return by value and reading-only access.
- Drill: arrays and vectors.
- Write a function that copies a C-style string into free store memory and returns a pointer to it. Use dereference
operator *
, instead of subscriptingoperator[]
; and no standard library functions. - Write a function that finds the first occurrence of a C-style string
x
ins
; without any standard library functions and with the use of the dereferenceoperator *
instead of subscriptingoperator[]
. - 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.
- Test the functions for non-zero terminated strings. Modify the functions to handle non-zero terminated strings.
- Write a function,
cat_dot()
, that concatenated two strings with a dot in between. - Modify
cat_dot()
function to concatenate two strings, adding a separator in between, passed as third argument. - Rewrite
cat_dot()
for c-style strings as input parameters; let it return a c-string on the heap. - 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.
- 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.
- 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.
- Look up and implement a skip list. (Not an easy exercise).
- Implement a version of the game "Hunt the Wumpus". Make it work via the console.
- Try this 1: Consider problems in function
resize()
: "Out of range error" in vector element access. - Try this 2: add
try-catch
blocks in functionsuspicious()
at all the places where resources are released. - Try this 3: modify function
reserve()
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. - Drill: exercises on
templates<\>
. - Write a template function that accumulates a
std::vector
of elements of an object of any type to which elements can be added. - Write a template function that takes two
std::vector
s as arguments and returns their inner product. - Write a template
class 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. - Modify
class 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
. - Define a
class Int
having a single member of typeint
. Define constructors, assignment,operators +
,-
,/
,*
, I/Ooperators <
,operator >>
. - Define a template
class Number
ofT
having a single member of any valid numeric type. Define constructors, assignment,operators+
,-
,/
,\*
, I/Ooperators <
,operator >
. - Redo Exercise 2, i.e. find the inner product of two vectors of using types
Number
ofT
. - Implement the allocator from §19.3.6 using
malloc()
andfree()
. Get thevector
as defined by the end of §19.4 to work for a few simple test cases. - Re-implement
vector::operator()
(§19.2.5) using an allocator §19.3.6 for memory management. - Implement a simple
auto_ptr
supporting: constructor, destructor,operator->
,\*
, andrelease()
. - Design and implement a
counted_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
. - 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.
- 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 by
new
. Add copy constructor and copy assignment and observe where copying is done. - 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.
- 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".
- Define a vector so
sizeof( 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.
- Try this 1: modify the existing code and remove the ugliness.
- Try this 2: remove errors from the modified code.
- Try this 3: Write a function
void 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[]
. - Try this 4: find and remove the error in the code.
- Try this 5: Implement
push_front()
forvector
and compare it topush_back()
. - Try this 6: Modify the function
advance()
to accept negative argument. - Try this 7: For each array of
char
,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. - Try this 8: Redo the previous Try This using containers of type
int
, initialized to{ 1, 2, 3, 4, 5 }
. - Drill: Use
std::array
,std::vector
,std::list
. Definecopy()
andstd::find()
. - Do all the Try This exercises.
- Get the "Jack and Jill" example from §20.1.2 to work. Use input from a couple of small files to test it.
- Look the palindrome example from §18.6; redo the Jack and Jill example from §20.1.2 using that variety of techniques.
- Find and fix errors in Jack and Jill in §20.3.1 by using STL techniques throughout.
- Define
<operator
and>operator
forstd::vector
. - Write find and replace function for
class Document
based on §20.6.2. - Find the lexicographically last string in an unsorted
std::vector<std::string>
. - Define a function that counts the number of characters in
Document
. - Define a function that counts the number of words in
Document
, where word is defined as: "white space separated sequence of characters" or "sequence of alphabetic characters". - Define a function that counts the number of words in
Document
, where the white space string is defined via function's argument. - Give a list
std::list
ofint
as a (by - reference) parameter, make astd::vector
double
and copy the elements of the list into it. Verify the copy was correct and complete. Print the elements sorted in increasing value. - Complete the definition of
List
from §20.4.1 - 2 and gethigh()
example to run. Allocate aList
to represent one past the end. - Modify the solution to the previous exercise to use
0
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. - Define a singly-linked list,
slist
, in the style ofstd::list
. Which operations fromList
should be kept? - Define a
pvector
to be likevector
of pointers except that it contains pointer to objects and its destructor deletes each object. - Define an
ownership_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 aredelete
d by the destructor). - Define a range-checked iterator for
vector
(a random-access iterator). - Define a range-checked iterator for
list
(a bidirectional iterator). - Compare
vector
andlist
. Generate N 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.)
- Try This 1: Write, test the functions
find()
and construct an argument for their being equivalent. - Try This 2: Why using implicit parameters could lead to obscure errors. List three examples where they should be avoided.
- Try This 3: Define a
std::vector
ofRecord
, initialize it with four Records of your choice, and compute their total price using the function in §21.5.2. - Try This 4: Write the example from §21.6.3 and get it to run.
- Try This 5: Write a small program using
#include <unordered_map>
. - 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).
- Drill 1:
algorithms
withstd::vector
andstd::list
. - Drill 2:
algorithms
withstd::map
. - Drill 3:
algorithms
withstd::vector<int>
andstd::vector<double>
. - Do all Try this exercises (in case you haven't).
- Find a reliable STL documentation and list every standard library algorithm.
- Implement
count()
yourself. Test it. - Implement
count_if()
yourself. Test it. - Reimplement
count()
andcount_if()
as if there is noend()
iterator. - Redo §21.6.5 but with
std::set<Fruit*>
instead. Provide a comparison operationFruit_comparison
, forstd::set<Fruit*, Fruit_comparison>
. - Implement a
binary_search()
function forstd::vector
andstd::list
. Test it. How much do they resemble each other? - Take the word frequency example from §21.6.1 and and modify it to to output its lines in order of frequency.
- Define an
Order
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()
; - Provide a GUI interface for entering
Order
s into files. - Provide a GUI interface for querying a file of
Orders
; e.g., "Find all orders from Joe," "Find the total value of orders in file Hardware," and "List all orders in file Clothing." - "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).
- 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."
- Provide a GUI for the previous exercise.
- Define programming.
- Define programming language.
- Which of the chapter vignettes were written by a scientist? Write a paragraph with the contribution of each scientist.
- Which of the chapter vignettes were written not by a scientist?
- Write a
"Hello, World!"
program in each of the languages mentioned in this chapter. - 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.
- 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.
- What is C++ used for and why? Write a 10- to 20- page report.
- What is C used for and why? Write a 10- to 20-page report.
- 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?
- Who currently holds the Lucasian Chair in Cambridge?
- Of the language designers mentioned in this chapter, who has a degree in mathematics? Who does not?
- Of the language designers mentioned in this chapter, who has a Ph.D.? In which field? Who does not have a Ph.D.?
- 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.
- Write a program that, given a file of (name,year) pairs, such as (Algol,1960) and (C,1974), graphs the names on a timeline.
- 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.
- 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).
- Try this 2: Write a brief explanation of the new terms used in the current section of the chapter.
- 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\.)
. - Drill: Find out if
regex
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. - 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 ....
- Add a
multimap
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. - Modify the email example from §23.4 to use regular expressions to find the subject and sender.
- Apply the previous program on real list of emails and extract the lines containing the subject.
- Compare
std::multimap
againststd::unordered_multimap
, having in mind that the latter doesn't take advantage of ordering. - 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. - Write a program that finds redit card numbers in a file and displays the line containing the date and its number.
- Write a program that finds a pattern in a file and displays the line containing the pattern and its number.
- Using
eof()
(§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. - Modify the table-checking program from §23.9 to write a new table where the rows with the same initial digit are merged.
- Modify the table-checking program from §23.9 to see if the number of students is increasing or decreasing over the years in question.
- Write a program, based on the program that finds lines containing dates, that finds all dates and reformats them to the ISO
yyyy/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. - Does dot
(.)
match'\n'
? Write a program to find out. - 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. - Describe a pattern that cannot be expressed as a regular expression.
- Prove that the pattern found in the previous exercise really isn't a regular expression.
- Try this 1: sum a the fraction
1/n
n
times and observe the result. Is it1
? Rounding Error. - Try this 2: Run the examples from §24.2 showing truncation, overflow and underflow examples due to intertype assignments, implicit conversion and algebraic calculations.
- Drill 1: Print the size of a
char
, ashort
, anint
, along
, afloat
, adouble
, anint*
, and adouble*
. (usesizeof
, notlimits
). - Drill 2: Print out the size as reported by
sizeof
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)
. - Drill 3: Print out the elements of the matrices from the previous exercise.
- Drill 4: Write a program that takes ints from d n and outputs the
sqrt()
of eachint
, or "no square root" ifsqrt(x)
is illegal forsome
x (i.e., check yoursqrt()
return values). - Drill 5: Read ten floating-point values from input and put them into a
Matrix
ofdouble
. Matrix has nopush_back()
so be careful to handle an attempt to enter a wrong number of doubles. Print out theMatrix
. - 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). - Drill 7: Read ten
complex
ofdouble
s fromstd::cin
and put them into aMatrix
. Calculate and output the sum of the tencomplex
numbers. - Drill 8: Read six
int
s into a2D Matrix
ofint
,m(2, 3)
and print them out. - The function arguments
f
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. - Do, the previous, Exercise 1 again, but with function objects, rather than functions.
- Write an
apply(f,a)
that can takes avoid f(T&)
, aT f(const T&)
, and their function object equivalents. Hint:Boost::bind
. - Get the Gaussian elimination program to work; that is, complete it, get it to compile, and test it with a simple example.
- Try the Gaussian elimination program with
A={ {O 1} {1 O} }
andb={ 5 6 }
and watch it fail. Then, tryelim_with_partiat_pivot()
. - In the Gaussian elimination example, replace the vector operations
dot_product()
andscale_and_add()
with loops. Test, and comment on the clarity of the code. - Rewrite the Gaussian elimination program without using the Matrix library; that is, use built-in arrays or vectors instead of Matrices.
- Animate the Gaussian Elimination.
- Rewrite the non-member
apply()
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. - How random is your
rand()
? 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. - Write a
swap_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()
. - Implement:
Matrix operator multiplication (2DMatrix&, 1DMatrix&);
, i.e. tensor-vector dot product andMatrix operator+ (Matrix&, Matrix&);
for randomly multidimensional matrices.
- Try This 1: Replace
333
in the example with10
and run the example again. What result would you expect? What result did you get? - Тry This 2: Before reading further, try to see how many errors you can find in
f()
in §25.4.3. Specifically, which of the calls ofpoor()
could cause the program to crash? - 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.
- Try This 4: Inspect the loop in §25.5.3 with signed
char
as loop variable andunsigned char
as termination variable. Why it's infinite? - Try This 5: Draw out the bit patterns on a piece or paper. Using paper, then figure out what the answer would be for
si = 128
in §25.5.3. Then run the program to see if your machine agrees. - Drill 1: Bit shifting and multiplication.
- Drill 2: Unsigned short Bit manipulations.
- Exercise 1: Do Try This Exercise.
- Hexspeak.
- Integer bit patterns.
- Add the bitwise logical operators
&
,|
,^
, and~
to the calculator from Chapter 7. - Write an infinite loop. Execute it.
- 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.
- Write out the hexadecimal values from
0
to400
; and from-200
to200
. - Write out the numerical values of each character on your keyboard.
- Without using any standard headers (such as
limits
or documentation, compute the number of bits in anint
and determine whetherchar
issigned
orunsigned
on your implementation. - Look at the bitfield example from §25.5.5. Write an example that initializes a
PPN
, 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. - Redo previous exercise using
bitset
. - Write out the clear text of the example from §25.5.6.
- Implement a simple
vector
that can hold at mostN
elements allocated from a pool. Test it forN == 1000
andinteger
elements. - Measure the time it takes to de / allocate
10000
objects of random sizes in[10000:0)
- byte range. Do this twice: once deallocate in reverse order and once deallocate in random order. - 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.
- Proof that
Array_ref
handles inheritance correctly by trying to get aRectangle\*
intostd::vector<Circle\*>
usingArray_ref<Shape\*>
, without using casts or other operations involving undefined behaviour.
- Implement a Binary Search algorithm by yourself. How do you know it is correct?
- Drill 1: Implement the input operator for
Test
from §26.3.2.2. - 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.
- 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. - Drill 4: Repeat these tests for sequences of strings, such as:
{ Bohr Darwin Einstein Lavoisier Newton Turing }
. - Exercise 1: Run your binary search algorithm from §26.1 wilt the tests presented in §26.3.2.1.
- Modify the testing of
binary_search()
to deal with arbitrary element types. Then, test it withstd::string
sequences andfloat
sequences. - Repeat the exercise in §26.2.1 with the version of
binary_search
that takes a comparison criterion. Make a list of new opportunities for errors introduced by that extra argument. - Devise a format for test data so that you can define a sequence once and run several tests against.
- Add a test to the set of
binary_search
tests to try to catch the (unlikely) error of abinary_search
modifying the sequence. - Modify the calculator from Chapter 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.
- Test the "simple text editor" from §20.6.
- 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 call
Circle(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. - Add a text-based output format for the graphics interface library. For example, when a call
Circle(Point(0,1),15)
is executed, a string like: "Circle(Point(0,1),15)" should be produced on an output stream. - Use the text-based interface from Exercise 9 to write a better test for the graphical interface library.
- Time the sum example from §26.6 with
m
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. - Write a program that generates random floating-point numbers and sorts them using
std::sort
. Measure the time used to sort500,000
doubles and5,000,000
doubles. - Write a program that generates random length, within
[0,100)
,std::string
s and sorts them usingstd::sort
. Measure the time used to sort500,000
and5,000,000
strings. - Repeat the previous exercise, except using a
std::map
rather than astd::vector
so that we don't need to sort.
- Try This 1: Test
cat()
. 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. - Is this implementation of
strcpy()
correct? Explain why. - 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.
- Drill 1: Write a
"Hello, World!"
program in C, compile it, and run it. - Define two variables holding
"Hello"
and"World!"
respectively; concatenate them with a space in between; and output them asHello, World!
. - Define a C function that takes a
char*
parameterp
and anint
parameterx
and prints out their values in this format:p
is"foo"
andx
is7
. Call it with a few argument pairs. - Exercise 1: Implement versions of
strlen()
,strcmp()
, andstrcpy()
. - Complete the intrusive list example in §27.9 and test it using every function.
- "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 the
struct
definitions, to use macros, whatever. - If you didn't already, write a C++ version of the intrusive list example in §27.9 and test it using every function.
- Compare the results of Exercises 3 and 4.
- Change the representation of
Link
andList
from §27.9 without changing the user interface provided by the functions. AllocateLink
s in an array ofLink
s and have the members:first
,last
,prev
, andnext
beint
s (indices into the array). - What are the advantages and disadvantages of intrusive containers compared to C++ standard (non-intrusive) containers? Make lists of pros and cons.
- 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.
- 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 called
qsort()
; look it up somewhere. Alternatively, insert the words into an ordered list as you read them. There is no C standard library list. - Make a list of C language features adopted from C++ or C with Classes (§27.1).
- Make a list of C language features not adopted by C++.
- 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. - Write a program that does the equivalent of
string 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 ofchar
s. - Write a function that takes an array of
int
s 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. - 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 derived
draw()
just printing out the name of their class. Use only language features and library facilities available in standard C. - Use macros to obscure (simplify the notation for) the implementation in the previous exercise.
===
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/
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 clarity braces ,{ }
, are on a new line:
int main() { // Code // indentation // is // 4 // spaces. }
Names of variables and functions start with lower case and contain upper case or underscore "_"
, in case of complex names; classes and namespaces start with upper case. Example:
namespace MyExample { int var; int func (int par); int res_var; class ObjectOriented { }; }
1.Main (Execution) files, FileName.cpp
, contain the included compiler libraries
and custom libraries, followed by the main()
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 files FileNameDef.cpp
contain class/function implementations,
separated either by:
----------------------------
or
===========================
with comments before the body of definition:
/* Function: Use: Description */
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 copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 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 THE SOFTWARE.