JirR02 e5548947e2 Exercise 9
Added Exercise 9 to repository
2025-04-21 23:47:45 +02:00
..
2025-04-21 23:47:45 +02:00

Task 2: Understanding struct & classes

/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

Consider the following definitions:

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];

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
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;
};

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

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;

```


Made by JirR02 in Switzerland 🇨🇭