Exercise 7

Added Exercise 7 to Repository
This commit is contained in:
2025-04-07 08:56:57 +02:00
parent bfc1a7a2b0
commit c71d2e026f
6 changed files with 471 additions and 7 deletions

View File

@@ -0,0 +1,71 @@
#+title: Task 1: Recursive function analysis
#+author: JirR02
/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
:PROPERTIES:
:CUSTOM_ID: task
:END:
For each of the following recursive functions:
1.
#+begin_src cpp
bool f(const int n) {
if (n == 0) return false;
return !f(n - 1);
}
#+end_src
2. [@2]
#+begin_src cpp
void g(const int n) {
if (n == 0) {
std::cout << "*";
return;
}
g(n - 1);
g(n - 1);
}
#+end_src
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
:PROPERTIES:
:CUSTOM_ID: solution
:END:
#+begin_src markdown
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$
#+end_src