JirR02 c6b006c2a1 Exercise 7
Added Exercise 7 to the repository
2025-04-07 08:43:53 +02:00
..
2025-04-07 08:43:53 +02:00

Task 1: Recursive function analysis

/This task is a text based task. You do not need to write any program/C++ file: the answer should be written in main.md (and might include code fragments if questions ask for them)./

Task

For each of the following recursive functions:

bool f(const int n) {
if (n == 0) return false;
return !f(n - 1);
}
void g(const int n) {
if (n == 0) {
std::cout << "*";
return;
}
g(n - 1);
g(n - 1);
}
  1. Formulate pre- and post conditions.
  2. Show that the function terminates. Hint: No proof expected, proceed similar as with the lecture example of the factorial function.
  3. Determine the number of functions calls as mathematical function of parameter n. Note: include the first non-recursive function call.

Solution

1. i) Pre- and post conditions

```c++
// PRE: n is a positive integer
// POST: returns true if n is even and false if n is odd.
```
  1. The function plain|f terminates because it has a termination condition. It will terminate once n reaches 0. If the number is negative, it will be in an infinite loop.
  2. \(\text{Calls}_{f}(n) = n\)
    1. Pre- and post conditions
// PRE: n is a positive integer
// POST: print 2^n *
  1. The function plain|g terminates because it has a termination condition. It will terminate once n reaches 0. If the number is negative, it will be in an infinite loop.
  2. \(\text{Calls}_{g}(n) = 2^n\)