JirR02 7b86ebfe6a Exercise 3
Added Exercise 3 with solutions and README to Repository
2025-03-07 23:04:40 +01:00
..
2025-03-07 23:04:40 +01:00
2025-03-07 23:04:40 +01:00

This task is a mixed text/programming task. You need to update the content of loop.cpp according to the instructions provided in the file. For the code part, please check the autograder output.

Task

Consider the following program:

int n;
std::cin >> n;

int x = 1;
if (n > 0) {
  bool e = true;
  do {
    if (--n == 0) {
      e = false;
    }
    x *= 2;
  } while (e);
}
std::cout << x << std::endl;
  1. Describe the output of the program as a function of its input n.
  2. For which values of n do you expect a correct output x? Explain why.
  3. Show that this program terminates for all values of n found in (2). Hint: Make an argument based on the following idea. First prove that the program terminates for the n=0 and n=1. Then show that it terminates for any other n knowing that it terminates for n-1. This creates a domino effect where the fact that the program terminates for n=1 proves that the program must also terminate for n=2, and this in turn proves that the program must terminate for n=3, and so on. This technique is called "proof by induction".
  4. Provide a more elegant implementation of this function using another type of loop. This part is autograded.