Exercise 9

Added Exercise 9 to repository
This commit is contained in:
2025-04-21 23:47:45 +02:00
parent 950098d35e
commit e5548947e2
4 changed files with 444 additions and 0 deletions

View File

@@ -0,0 +1,96 @@
#+title: Task 2: Understanding struct & classes
#+author: JirR02
/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
:PROPERTIES:
:CUSTOM_ID: task
:END:
Consider the following definitions:
1.
#+begin_src cpp
struct A {
int a;
double b;
int c;
};
A str = {1, 1.5, 2};
std::vector<int> vec = {1, 1, 3};
int& a = vec[0];
#+end_src
For each of the provided expressions state their /C++ type/ and /value/:
1. =str.a * str.b=
2. =str.b == vec[1]=
3. =str.a * str.b / str.c=
4. =vec[str.a] / str.c=
5. =a / 2 - str.b=
2. [@2]
#+begin_src cpp
class B {
public:
B(): vec(128) {
for (int i = 0; i < 128; ++i) {
vec[i] = 0;
}
}
// PRE: ...
// POST: ...
void add(const char c) {
++vec[c];
}
// PRE: ...
// POST: ...
int get(const char c) const {
return vec[c];
}
private:
std::vector<int> vec;
};
#+end_src
Determine PRE- and POST-conditions for the methods add and get. As these
methods are members functions of class B, PRE- and POST-conditions
should be derived taking the public interface of the class into account.
* Solution
:PROPERTIES:
:CUSTOM_ID: solution
:END:
#+begin_src markdown
1. `plain|`
1. Type: `cpp|double` / Value: `cpp|1.5`
2. Type: `cpp|bool` / Value: `cpp|true`
3. Type: `cpp|double` / Value: `cpp|0.75`
4. Type: `cpp|int` / Value: `cpp|0`
5. Type: `cpp|double` / Value: `cpp|-1.5`
2. ```c++
// PRE: 0 <= c < 128
// POST: Increments the value of the vector at position c
void add(const char c);
// PRE: 0 <= c < 128
// POST: Gets the value of the vector at position c
int get(const char c) const;
#+end_src
```
--------------
Made by JirR02 in Switzerland 🇨🇭