================= Possible Solution [TOC] ================= Some remarks: - In general some pseudo code hides many technical details. This has the advantage that the underlying concept of an algorithm becomes more evident. In order to write an actual implementation for the pseudo code we need to fill the gaps: - The pseudo code does not mention the type of the variables. But it makes sense to use some *unsigned* integer type. Here we used `unsigned long` but `unsigned char`, `unsigned int` or `unsigned long long` would be fine. You might have noticed that the exit code is always in the range from 0 to 255. So although `main`has return type `int` what we get with `echo$?` is an unsigned character byte. How exit codes are handled depends on the operating system (e.g. on Windows the exit code can be a 16 bit integer). - In the pseudo code we did not explicitly mention that functions are supposed to return the value of a local variable `result`. This has to be deduced in this case. For the implementation it means that each function has a return statement. Function factorial with for-loop ================================ :import: session07/factorial_for.c ---- SHELL(path=session07) ----------------------------------------------------- gcc -Wall -std=c11 -o factorial_for factorial_for.c ./factorial_for echo $? -------------------------------------------------------------------------------- Function factorial with while-loop ================================== :import: session07/factorial_while.c ---- SHELL(path=session07) ----------------------------------------------------- gcc -Wall -std=c11 -o factorial_while factorial_while.c ./factorial_while echo $? -------------------------------------------------------------------------------- Function factorial with recursive calls ======================================= :import: session07/factorial_rec.c ---- SHELL(path=session07) ----------------------------------------------------- gcc -Wall -std=c11 -o factorial_rec factorial_rec.c ./factorial_for echo $? -------------------------------------------------------------------------------- Note that this function uses the conditional expression `cond ? value_if_true : value_if_false`. You also can implement this with an if-statement: ---- CODE(type=c) -------------------------------------------------------------- unsigned long factorial(unsigned long n) { // return n>1 ? n*factorial(n-1) : 1; if (n>1) { return n*factorial(n-1); } else { return 1; } } --------------------------------------------------------------------------------