1.10 Exercises
1.10.1 Narrowing
Assign large values to different integer types with uniform initialization, i.e., using braces. For instance,
const unsigned c1{4000000000};
Does this compile on your machine? Try different values (including negative values) and different types and see what compiles on your platform. If possible, try other platforms by changing the machine or the compiler flags regarding the target platform.
1.10.2 Literals
Refactor your examples from Exercise 1.10.1 by using literal suffixes u and l as well as legal combinations thereof. If you like, you can change the variable/constant types to auto.
1.10.3 Operators
Program expressions that calculate the volumes and surfaces of different solid figures. Try to use as few parentheses as possible (in real life you may again apply as many as you want). Attempt to reuse common partial expressions by storing their results in intermediate variables.
1.10.4 Branching
Write a program that reads three numbers as double and prints the middle one. Optional: try expressing the same with ?:.
1.10.5 Loops
Find the zero of f = sin(5x) + cos(x) between 0 and 1 by interval nesting. For a given interval, split it in the middle and see on which side the sign of f is changing, then continue with this interval. Stop the calculation when the interval is smaller than 10−12 (so, we need double) and print the center of that interval with 11 digits as an approximated result. Hint: The result should be approximately 0.785. C++11 introduces the function signbit that is helpful here. Try different kinds of loops and think about which one feels most appropriate in this context.
1.10.6 I/O
Refactor Exercise 1.10.3 by writing all input parameters used in the calculation and all results to a file. Use a new line for a new set of values. Pay attention to leave a space between two numbers. Write a second program that reads the values from the file and compares it with the original ones.
1.10.7 Arrays and Pointers
Make a small program that creates arrays on the stack (fixed-size arrays) and arrays on the heap (using allocation). Use valgrind (or some Visual Studio tool on Windows) to check what happens when you do not delete them correctly or you use the wrong delete (array vs. single entry).
1.10.8 Functions
Write functions that convert SI units like meter2km and/or convert between SI and old-fashioned Anglo-American units like usgallon2liter. Test your implementations with assert. Use an ɛ-environment to deal with floating-point rounding issues, i.e. that the magnitude of the difference between computed and expected values is smaller than some predefined ɛ.