4thExercises.pdf

(107 KB) Pobierz
X
Exercises
You cannot learn bicycling
from a correspondence course.
– anon
Exercises for Bjarne Stroustrup:
The C++ Programming Language (4th Edition).
Addison-Wesley
ISBN 978-0321563842.
Corrections, suggested improvements, and more exercises are welcome.
This version of the exercises is dated May 12, 2013.
X.1 Introduction
You can argue that programming is an art, a craft, a science, or even a branch of mathematics. In
any case, it inovolves some practical skills that cannot be learned simply by reading a book. The
skills have to be learned by trying to apply the principles and techniques learned from books, arti-
cles, lectures, etc.
This ‘‘appendix’’ contains exercises for the readers of TC++PL. They are sorted by chapter and
within a chapter roughly by difficulty. The exercises are mainly of the write-a-program variety.
Always write enough code for a solution to be compiled and run with at least a few test cases.
The exercises vary considerably in difficulty, so they are marked with an estimate of their diffi-
culty. The scale is exponential so that if a (∗1) exercise takes you ten minutes, a (∗2) might take an
hour, and a (∗3) might take a day. The time needed to write and test a program depends more on
your experience than on the exercise itself. A (∗1) exercise might take a day if you first have to get
acquainted with a new computer system in order to run it. On the other hand, a (∗5) exercise might
be done in an hour by someone who happens to have the right collection of programs handy. Many
of the exercises marked (∗1) and (∗2) can be thought of as similar to the drills that musicians, ath-
letes, and learners of a new natural language do to prevent unfamiliarity with simple subtasks from
impeding the performance of more challenging tasks. They are not intellectual challenges in their
own right.
2002
Exercises
Appendix X
Any book on programming in C can be used as a source of extra exercises for Part II (The
basics;
Chapters 6-15). Any book on data structures and algorithms can be used as a source of
exercises for Parts III (Abstraction
Mechanisms;
Chapters 16-29) and IV (The
Standard Library;
Chapters 30-44).
I place this collection of exercises on the web because
• I do want to add another 80 pages to an already thick book.
• I want to add more exercises over the years.
• I hope readers will suggest improvements and new exercises so that eventually the set of
exercises will be massive – more extensive and useful than I could make it on my own.
I cannot promise the numbering of exercises to be stable as I add exercises. I plan for relative sta-
bility after an initial peiod of major changes, but for now expect details of numbering to change.
X.2 The Structure of This Book
The exercises for this chapter focus on the history and philosophy of C++. They mostly aim at an
undestanding of the rationale behind C++ facilities. Do not attempt these until you have a basic
understanding of C++.
[1] (∗1) What does (∗2.5) mean for an exercise?
[2] (∗2) Briefly describe the design aims of C++ and comment on the extent to which C++ meets
those.
[3] (∗4) Write an essay: What can a good programming language do for you and what can’t you
expect it to help with?
[4] (∗1) What are the main programming styles supported by C++?
[5] (∗2.5) List five language features offered by the 1985 version of C++, five features added by
C++98, and finally five new features added by C++11. In each case, order the features in
order of importance and for each feature write a sentence describing its role in programming.
[6] (∗3) Describe the difference between dynamic (run-time) and static (compile-time) type
checking and outline the strengths and weaknesses of each.
[7] (∗1.5) List the major components of the C++ standard library.
[8] (∗1.5) List five libraries that you would have liked to be part of the standard.
[9] (∗1) List three (or more) advantages from having a library as part of the standard.
[10] (∗3) List 20 major real-world C++ applications.
[11] (∗2) From §1.3 pick five suggestions that to you looks most likely to help improve your pro-
gramming style.
[12] (∗2) Make a ‘‘top-ten list’’ of helpful design and programming rules. Hint: §X.2.
X.3 A Tour of C++: The Basics
[1]
[2]
[3]
When first reading this chapter, keep a record of information that was new or surprising to
you. Later, use that list to focus your further studies.
(∗1) What does a compiler do? What does a linker do?
(∗2) Get the ‘‘Hello, world!’’ program (§2.2.1) to run. This is not an exercise in program-
ming. It is an exercise to test your use of your edit-compile-link-execute tool chain.
Section X.3
A Tour of C++: The Basics
2003
[4]
[5]
[6]
[7]
(∗1) List three (or more) C++ compilers.
(∗1) Write out a
bool
, a
char
, an
int
, a
double
, and a
string
.
(∗1) Read in a
bool
, a
char
, an
int
, a
double
, and a
string
.
(∗2) What is an invariant and what good might it do?
X.4 A Tour of C++: Abstraction Mechanisms
[1]
[2]
When first reading this chapter, keep a record of information that was new or surprising to
you. Later, use that list to focus your further studies.
(∗2) Give five examples of concrete types that are built-in types in C++. Give five examples
of concrete types that are not built-in types in C++.
X.5 A Tour of C++: Containers and Algorithms
When first reading this chapter, keep a record of information that was new or surprising to
you. Later, use that list to focus your further studies.
[2] (∗1) List five standard-library containers.
[3] (∗1) List five standard-library algorithms.
[4] (∗1) List five standard-library headers.
[5] (∗1.5) Write a program that reads a name (a
string
) and an age (an
int
) from the standard
input stream
cin
. Then output a message including the name and age to the standard output
stream
cout
.
[6] (∗1.5) Redo §X.5[5], storing several (name,age) pairs in a class. Doing the reading and writ-
ing using your own
>>
and
<<
operators.
[7] (∗2) Initialize a
vector<int>
with the elements
5
,
9
,
−1
,
200
, and
0
. Print it. Sort is, and print it
again.
[8] (∗1) Repeat §X.5[7] with a
vector<string>
initialized with
"Kant"
,
"Plato"
,
"Aristotle"
,
"Kierkegard"
, and
"Hume"
.
[9] (∗1) Open a file for writing (as an
ofstream
) and write a few hundred integers to it.
[10] (∗1) Open the file of integers from §X.5[9] for reading (as an
ifstream
) and read it.
[1]
X.6 A Tour of C++: Concurrency and Utilities
[1]
[2]
[3]
When first reading this chapter, keep a record of information that was new or surprising to
you. Later, use that list to focus your further studies.
(∗1.5) Write a program with two
tread
s: one that writes
hello
every second and one that
writes
world!
every second.
(∗2) Time a loop. Write out the time in milliseconds. Do this for the default setting of your
compiler and for a setting using an optimizer (e.g.,
−O2
or "release"). Be careful not to have
the optimizer eliminate your whole loop as dead code because you did not use a result.
(∗2) Repeat the histogram drawing example from §5.6.3 for a
normal_distribution
and
30
rows.
[4]
2004
Exercises
Appendix X
[5]
(∗1.5) Use a
regex
to find all decimal numbers in a file.
X.7 Types and Declarations
[1]
[2]
[3]
[4]
[5]
(∗2) Get the ‘‘Hello, world!’’ program (§2.2.1) to run. This is not an exercise in program-
ming. It is an exercise to test your use of your edit-compile-link-execute tool chain.
(∗1) Write a program that prints
signed
if plain
char
s are signed on your implementation and
unsigned
otherwise.
(∗1.5) Find 5 different C++ constructs for which the meaning is undefined (§6.1). (∗1.5)
Find 5 different C++ constructs for which the meaning is implementation-defined (§6.1).
(∗1) Find 10 different examples of nonportable C++ code.
(∗1) For each declaration in §6.3, do the following: If the declaration is not a definition, write
a definition for it. If the declaration is a definition, write a declaration for it that is not also a
definition.
(∗1.5) Write a program that prints the sizes of the fundamental types, a few pointer types, and
a few enumerations of your choice. Use the
sizeof
operator.
(∗1.5) Write a program that prints out the letters
'a'
..
'z'
and the digits
'0'
..
'9'
and their integer
values. Do the same for other printable characters. Do the same again but use hexadecimal
notation.
(∗2) What, on your system, are the largest and the smallest values of the following types:
bool
,
char
,
short
,
int
,
long
,
long long
,
float
,
double
,
long double
,
unsigned
and
unsigned long
.
(∗1) What are the sizes (in number of
char
s) of the types mentioned in §X.7[8]?
(∗1.5) What are the alignments (in number of
char
s) of the types mentioned in §X.7[8]?
(∗2) Draw a graph of the integer and fundamental types where a type points to another type if
all values of the first can be represented as values of the second on every standards-conform-
ing implementation. Draw the same graph for the types on your favorite implementation.
(∗1) What is the longest local name you can use in a C++ program on your system? What is
the longest external name you can use in a C++ program on your system? Are there any
restrictions on the characters you can use in a name?
(∗1.5) Write a loop that prints out the values
4
,
5
,
9
,
17
,
12
without using an array or a
vector
.
[6]
[7]
[8]
[9]
[10]
[11]
[12]
[13]
X.8 Pointers, Arrays, and References
[1]
(∗1) Write declarations for the following: a pointer to a character, an array of 10 integers, a
reference to an array of 10 integers, a pointer to an array of character strings, a pointer to a
pointer to a character, a constant integer, a pointer to a constant integer, and a constant
pointer to an integer. Initialize each one.
(∗1.5) What, on your system, are the restrictions on the pointer types
char∗
,
int∗
, and
void∗
?
For example, may an
int∗
have an odd value? Hint: alignment.
(∗1) Use an alias (
using
) to define the types
unsigned char
,
const unsigned char
, pointer to
integer, pointer to pointer to
char
, pointer to array of
char
, array of 7 pointers to
int
, pointer to
an array of 7 pointers to
int
, and array of 8 arrays of 7 pointers to
int
.
[2]
[3]
Section X.8
Pointers, Arrays, and References
2005
[4]
[5]
[6]
[7]
[8]
(∗1) Given two
char∗
s pointing into an array, find and output the number of characters
between the two pointed-to characters (zero if they point to the same element).
(∗1) Given two
int∗
s pointing into an array, find and output the number of
int
s between the
two pointed-to
int
s (zero if they point to the same element).
(∗2) What happens when you read and write beyond the bounds of an array. Do a few exper-
iments involving a global array of
int
s , a local array of
int
s, an array of
int
s allocated by
new
,
and a member array of
int
s. Try reading and writing just beyond the end and far beyond the
end. Try the same for just before and far before the beginning. See what happens for differ-
ent optimizer levels. Then try hard never to do out-of-range access by mistake.
(∗1) Write a function that swaps (exchanges the values of) two integers. Use
int∗
as the argu-
ment type. Write another swap function using
int&
as the argument type.
(∗1.5) What is the size of the array
str
in the following example:
char str[] = "a short string";
[9]
[10]
[11]
[12]
[13]
What is the length of the string
"a short string"
?
(∗1) Define functions
f(char)
,
g(char&)
, and
h(const char&)
. Call them with the arguments
'a'
,
49
,
3300
,
c
,
uc
, and
sc
, where
c
is a
char
,
uc
is an
unsigned char
, and
sc
is a
signed char
.
Which calls are legal? Which calls cause the compiler to introduce a temporary variable?
(∗1) Define an array of strings in which the strings contain the names of the months. Print
those strings. Pass the array to a function that prints those strings.
(∗2) Read a sequence of words from input. Use
Quit
as a word that terminates the input.
Print the words in the order they were entered. Don’t print a word twice. Modify the pro-
gram to sort the words before printing them.
(∗2) Write a function that counts the number of occurrences of a pair of letters in a
string
and
another that does the same in a zero-terminated array of
char
(a C-style string). For example,
the pair
"ab"
appears twice in
"xabaacbaxabb"
.
(∗2) Run some tests to see if your compiler really generates equivalent code for iteration
using pointers and iteration using indexing (§7.4.1). If different degrees of optimization can
be requested, see if and how that affects the quality of the generated code.
X.9 Structures, Unions, and Enumerations
[1]
(∗1) Define a
struct
with a member of each of the types
bool
,
char
,
int
,
long
,
double
, and
long
double
. Order the members so as to get the largest size of the
struct
and the smallest size of
the
struct
.
(∗1.5) Define a table of the names of months of the year and the number of days in each
month. Write out that table. Do this twice; once using an array of
char
for the names and an
array for the number of days and once using an array of structures, with each structure hold-
ing the name of a month and the number of days in it.
(∗1.5) Find an example where it would make sense to use a name in its own initializer.
(∗1.5) Define a
struct Date
to keep track of dates. Provide functions that read
Date
s from
input, write
Date
s to output, and initialize a
Date
with a date.
[2]
[3]
[4]
Zgłoś jeśli naruszono regulamin