#+TITLE: Fixing Functions

/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:

What are the problems (if any) with the following functions? Fix them and find appropriate [[https://en.wikipedia.org/wiki/Precondition][pre-]] and [[https://en.wikipedia.org/wiki/Postcondition][postconditions]].

1. function is_even:

#+begin_src cpp
bool is_even(int i) {
    if (i % 2 == 0) return true;
}
#+end_src

1. function invert:

   #+begin_src cpp

double invert(int x) {
    double result;
    if (x != 0) {
        result = 1.0 / x;
    }
    return result;
}
   #+end_src

**Hint**: The C++ compiler does not protect you from certain types of errors. Therefore, even if you run a program in Code Expert, it is not guaranteed that the behaviour you observe is the “real” one. We have prepared a [[https://lec.inf.ethz.ch/ifmp/2023/guides/tracing/intro.html][programming tracing handout]] that shows how to execute a program with a pen and paper and which conditions indicate bugs in the executed program not caught by the C++ compiler.

* Solution

#+begin_src markdown
Please write your solution here.
For your convenience we have added a template for your answers below.

Note: Remember to also describe the problem of the function.

# Function `c++|is_even`:

The problem with this function is that it does not return a bool if the number `i` is uneven.

```c++
// PRE:  n/a
// POST: returns true if i is even. If not it returns false.
bool is_even(int i) {
  if (i % 2 == 0) return true;
  else return false;
}
```

# Function `c++|invert`:

The problem with this function is

```c++
// PRE: x is positive or negative but not zero.
// POST: returns inverse with respect to multiplication of x.
double invert(int x) {
  // TODO: Fix code below.
  if (x != 0) {
      return 1.0 / x;
  }
  else
    std::cout << "0 has no inverse!";
}
```

#+end_src

-----

Made by JirR02 in Switzerland 🇨🇭
