Exercises
Solutions to selected exercises
can be found in the electronic document The Thinking in C++ Annotated
Solution Guide, available for a small fee from
https://www.BruceEckel.com
- Modify Hello.cpp so
that it prints out your name and age (or shoe size, or your dog’s age, if
that makes you feel better). Compile and run the
program.
- Using
Stream2.cpp and Numconv.cpp as guidelines, create a program that
asks for the radius of a circle and prints the area of that circle. You can just
use the ‘*’ operator to square the radius. Do not try to
print out the value as octal or hex (these only work with integral
types).
- Create a
program that opens a file and counts the whitespace-separated words in that
file.
- Create a
program that counts the occurrence of a particular word in a file (use the
string class’ operator ‘==’ to find the
word).
- Change
Fillvector.cpp so that it prints the lines (backwards) from last to
first.
- Change
Fillvector.cpp so that it concatenates all the elements in the
vector into a single string before printing it out, but don’t try
to add line
numbering.
- Display a
file a line at a time, waiting for the user to press the “Enter” key
after each
line.
- Create a
vector<float> and put 25 floating-point numbers into it using a
for loop. Display the
vector.
- Create
three vector<float> objects and fill the first two as in the
previous exercise. Write a for loop that adds each corresponding element
in the first two vectors and puts the result in the corresponding element
of the third vector. Display all three
vectors.
- Create
a vector<float> and put 25 numbers into it as in the previous
exercises. Now square each number and put the result back into the same location
in the vector. Display the vector before and after the
multiplication.
[25]
The boundary between compilers and interpreters can tend to become a bit fuzzy,
especially with Python, which has many of the features and power of a compiled
language but the quick turnaround of an interpreted language.
[26]
Python is again an exception, since it also provides separate
compilation.
[27]
I would recommend using Perl or Python to automate this task as part of your
library-packaging process (see www.Perl.org or www.Python.org).
[28]
There are actually a number of variants of getline( ), which will be
discussed thoroughly in the iostreams chapter in Volume 2.
[29]
If you’re particularly eager to see all the things that can be done with
these and other Standard library components, see Volume 2 of this book at
www.BruceEckel.com, and also www.dinkumware.com.