Skip to content

Instantly share code, notes, and snippets.

@M0r13n
Last active August 15, 2019 13:25
Show Gist options
  • Save M0r13n/995bed8a9ea00c902f88ecd552de9a38 to your computer and use it in GitHub Desktop.
Save M0r13n/995bed8a9ea00c902f88ecd552de9a38 to your computer and use it in GitHub Desktop.
Super simple recursive factorial function in C.
#include <stdio.h>
#include <stdlib.h>
long factorial(long n) {
if (n == 0)
return 1;
else
return (n * factorial(n - 1));
}
int main(int argc, char **argv) {
char *ptr;
long number;
// check perquisites
if (argc != 2) {
printf("Exactly one character needed. I am going to die now :-(");
exit(1);
}
// convert user input to number
number = strtol(argv[1], &ptr, 10);
// there may was some malformed input
if (ptr[0] != 0) {
printf("Your input could not be parsed completely. Unparsed part is |%s|", ptr);
exit(1);
}
if (number < 0) {
printf("Number must be bigger or equal than 0.");
exit(1);
}
// this wont quite work out with our standard data types
if (number >= 21) {
printf("You should enter a number that is equal or less than 21, otherwise it cannot be stored in a long data type");
exit(1);
}
printf("The factorial of %ld is %ld\n", number, factorial(number));
exit(0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment