Skip to content

Instantly share code, notes, and snippets.

@Polda18
Last active December 2, 2018 12:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Polda18/c7bfca22c5c5db79b8a264e72230262a to your computer and use it in GitHub Desktop.
Save Polda18/c7bfca22c5c5db79b8a264e72230262a to your computer and use it in GitHub Desktop.
Recursive function example
#include <stdio.h>
#include <stdlib.h>
int factorial(int n);
int main(int argc, char* argv[])
{
if(argc > 1)
{
int number;
sscanf(argv[1], "%d", &number);
fprintf(stdout, "%d! = %d\n", number, factorial(number));
}
else
fprintf(stdout, "Usage: %s <number>\n", argv[0]);
return 0;
}
int factorial(int n)
{
if (n > 1)
return n * factorial(n - 1);
else
return 1;
}
@Polda18
Copy link
Author

Polda18 commented Feb 25, 2018

Thanks to quick bug report, logical error was corrected: return factorial(n - 1) replaced by return n * factorial(n - 1).

@Polda18
Copy link
Author

Polda18 commented Dec 2, 2018

This is very basic denotation and basically works. This but needs to sanitise wrong input (not a number, number is zero or negative), so it won't crash if user inputs foo instead of a positive number and won't output a number and obviously wrong answer when the user inputs zero or a negative number. Use it only as a scheme of how it would actually be used. The only part that is actually relevant here is the recursive factorial function. This obviously only applies to this particular recursive function. It only calls itself when conditions are met and return a known value otherwise, therefore preventing infinite recursion and stack overflow.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment