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;
- Describe the output of the program as a function of its input n.
- For which values of
n
do you expect a correct outputx
? Explain why. - 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 then=0
andn=1
. Then show that it terminates for any othern
knowing that it terminates forn-1
. This creates a domino effect where the fact that the program terminates forn=1
proves that the program must also terminate forn=2
, and this in turn proves that the program must terminate forn=3
, and so on. This technique is called "proof by induction". - Provide a more elegant implementation of this function using another type of loop. This part is autograded.