Possible Solution
Content |
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 mainhas 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
unsigned long n = 5; unsigned long factorial(unsigned long n) { unsigned long result = 1; for (unsigned long i=2; i<=n; ++i) { result *= i; } return result; } int main() { return factorial(n); }
thales$ gcc -Wall -std=c11 -o factorial_for factorial_for.c thales$ ./factorial_for thales$ echo $? 120 thales$
Function factorial with while-loop
unsigned long n = 5; unsigned long factorial(unsigned long n) { unsigned long result = 1; while (n>1) { result *= n; --n; } return result; } int main() { return factorial(n); }
thales$ gcc -Wall -std=c11 -o factorial_while factorial_while.c thales$ ./factorial_while thales$ echo $? 120 thales$
Function factorial with recursive calls
unsigned long n = 5; unsigned long factorial(unsigned long n) { return n>1 ? n*factorial(n-1) : 1; } int main() { return factorial(n); }
thales$ gcc -Wall -std=c11 -o factorial_rec factorial_rec.c thales$ ./factorial_for thales$ echo $? 120 thales$
Note that this function uses the conditional expression cond ? value_if_true : value_if_false. You also can implement this with an if-statement:
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; } }