JirR02 c71d2e026f Exercise 7
Added Exercise 7 to Repository
2025-04-07 08:56:57 +02:00
..
2025-04-07 08:56:57 +02:00

Task 1: Recursive function analysis

This task is a text based task. You do not need to write any program or 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.
```

ii) 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.

iii) $\text{Calls}_{f}(n) = n$

2. i) Pre- and post conditions

```cpp
// PRE: n is a positive integer
// POST: print 2^n *
```

ii) 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.

iii) $\text{Calls}_{g}(n) = 2^n$