JirR02 88e0b5ed69 Converted everything to orgmode
converted everything to orgmode and added solution to the README files
2025-03-31 08:40:43 +02:00
..
2025-03-31 08:40:43 +02:00

Task 1: Loop mix-up: Snippet 1

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

Task

Considering the snippet

int n;
std::cin >> n;
int f = 1;
if (n > 0) {
  do {
    f = f * n;
    --n;
  } while (n > 0);
}
std::cout << f << std::endl;
  1. Describe what it computes.
  2. Decide which of the other two kind of loops would fit better than the one it is currently using, and describe why.
  3. Rewrite the snippet into the loop you specified in (2). This part is autograded.

Important: The use of goto statements is prohibited.

Solution

#include "loop.h"
#include <iostream>

// Fill out the file with the required answers

/*

  Subtask 1: describe what the code snippet computes

  It calculates the factorial of the number inputed by the user.

*/

/*

  Subtask 2: decide which of the other two kind of loops would fit better, and
  describe why.

  Just a simple for loop would suffice the task of this code snippet, as we can
  define the condition in the for loop as well as the expression. This
  simplifies the code alot.

  Of course we could also include the edge case where the input n is 0 or
  smaller than zero. In this case an if statement would be more of use since we
  have to seperate the cases.

*/

/*
  Subtask 3: update the function below by rewriting the snippet into the
  loop you specified in (2)
*/

void loop() {

  int n;
  std::cin >> n;
  int f = 1;
  for (; n > 0; --n)
    f = f * n;

  std::cout << f << std::endl;
}

-——

Made by JirR02 in Switzerland 🇨🇭