Lecture "Programming" SS 2020 Problem Set 5: Exercise 1 (C++) Static & Dynamic Arrays

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 7

Lecture “Programming”

SS 2020

Problem Set 5
Simon Scheidegger

Exercise 1 (C++)

Static & dynamic arrays

Write a program which first reads in the number of values n. Then read in n values
from standard input. Normalize the loaded sequence so that the sum is 1. Print out the
normalised sequence in reverse order.

1. Set a maximum number of input values n max and allocate a static array of length n max .

2. Do the same using dynamic arrays so that the input size is not longer limited. One option to
achieve this is to use std::vector.

Hint: if you use the standard input mechanism std::cin, the input sequence can be read from a file
input.txt containing e.g. ”3 1 2 3” with

./main < input.txt

or generated by either of the following lines:

./main < <(echo 3 1 2 3)

echo 3 1 2 3 | ./main

Exercise 2 (C++)

Simpson numerical integration

The 1-dimensional Simpson integration approximates the function by a parabola in each


bin stretching from x to x + ∆x. For that one needs 3 function values at x, x + ∆x/2 and
x + ∆x. The integral over the interpolating parabola f ̃ (x) gives

In order to numerically integrate a function from a to b you discretized it to N bins and use the
interpolation formula within each bin. If you use regular a mesh (equally sized bins) with bin size
∆x = (b − a)/N then the complete formula for Simpson integration is
Write a program to implement the following numerical integration using Simpson’s rule

Hint for testing/debugging: The Simpson integration should integrate polynomials up to the 3rd
order precisely with any number of bins. So you may for instance integrate

with N = 1, 2, 3, 10 bins for testing purposes.

Exercise 3 (C++)

Simpson integration library using function pointers

1. Wrap the Simpson integration from the previous exercise into a function which takes as
arguments a pointer to the integrand, the integration interval and the number of bins. Check the
validity/correctness of input parameters using assertions. Put the function into a separate file.

2. Create a header file that declares the function. What are the preconditions and post-conditions?
Document this file thoroughly.

3. Write a make file that compiles the function for you. Make sure it only compiles
the files that have changed.

4. Compile a library libintegrate.a that contains your Simpson integration function.


Rewrite your make file to link against it.

Exercise 4 (C++)

Formatted output

1. In your main function, iterate over an appropriately increasing discretisation resolution (number
of bins) to investigate the improvement in accuracy.

2. Write your results into a file in the column format <resolution> <integral>, e.g.:

3 2.001
4 2.0003
10 2.00001

You can either use the standard file output mechanism std::ofstream("result.txt")
or print it to std::cout and redirect the output into a file:

./main > result.txt

3. Update your make file to generate the output file.

4. Optional: create a plot of the output file and integrate its generation into your make
file. You can use any plotting tool you prefer (gnuplot, a matplotlib script,...). One simple method is
this gnuplot one-liner:

gnuplot <(echo "set terminal png; set output 'result.png'; plot 'result.txt' with lines")

Exercise 5 (C++)

Operator overloading and template functions

This exercise focuses on the implementation of a new type describing the


group, and on the implementation of a generic power function working with all standard numeric
types, as well as our new .

a) Implementation of

To represent the group in C++, we will use the enumeration type:

enum Z2 { Plus , Minus } ;

The group operation will be implemented by overloading the * operator, i.e. we assign the correct
meaning to the expression

Z2 p = Plus , m = Minus ;
Z2 r = p∗m;

Every time we make use of the operator *, the C++ compiler is looking for the function
operator* with the correct types to be invoked. Note that the same is also valid for all operators: +,
−, (), [], <<, etc.
In our case, we need to define:

Z2 operator ∗ ( Z2 a , Z2 b ) ;

Furthermore, we want to be able to print our result in a nice form, i.e. using an expression such as
std::cout << r << std::endl;. We will therefore overload

ostream& operator<<(ostream& os , Z2 a ) ;

in such a way that Plus is printed for + and Minus for −. To implement the action of a group element
on a number, we will implement the following template functions (note that from the point of view
of C++, a*b is not necessarily the same as b*a):

template<c l a s s T> T operator ∗ (T a , Z2 b ) ;


template<c l a s s T> T operator ∗ ( Z2 a , T b ) ;

b) Implementation of generic power function We also want to implement a templated power


function which only relies on the multiplication, so that it can also be used on our
group:

template<c l a s s T> T mypow(T a , unsigned int n ) ;

Hint: In order to be generic, we provide a templated function identity_element, which


returns one for all numeric types. How can you overload such a function to provide the
identity element of the
group?

Exercise 6 (C++)

Simpson integration with function objects

In a previous exercise, we wrote a static library to perform the Simpson integration of sin(x) in the
region x ∈ [0, π], where the integrand was passed as a function pointer. In this exercise, implement
the Simpson integration of exp(−λx) in the region x ∈ [0, 1] by the use of a function object.

1. Rewrite the simpson function so that it works with function objects.

2. Introduce a template parameter for the type of the integration boundaries a and b.
What is its concept?
What happens if you call your function like simpson(0, 1, 128, func obj)?

Keep in mind (and make sure you know why) that you need to provide the definition and not just
the declaration in the header when templating the Simpson integration (i.e. you do not need the
simpson.cpp file anymore and you will not build a library as in the exercise above).
Exercise 7 (C++)

Trafficlight

What is the output of the following code? Can you guess it without running it?
Exercise 8 (C++)

Iterators

As we will see iterators provide the interface between containers and algorithms and thus play a key
role in most scientific programs. In this exercise we will provide an Iterator for the Array<T> class
discussed during the lecture (array.hpp is provided). Your goals for today will be:

i) Implement a forward iterator class.

ii) Make it a checked iterator (prevent illegal operations e.g. ++(array.end())).

iii) (Bonus) Upgrade your forward iterator to a bidirectional iterator.

Check iterators/iterator.hpp for a skeleton of the code and the precise requirements on
forward and bidirectional iterators. Make sure to add begin() and end() member functions to the
array class so that you may easily obtain iterators for your array. Check the
(iterators/main.cpp) for a simple program with which you may test some of the
functionality of your iterator.
Exercise 9 (C++)

Inheritance

Specify the output of the following code (without running it!).

You might also like