Last active
December 2, 2018 12:50
-
-
Save Polda18/c7bfca22c5c5db79b8a264e72230262a to your computer and use it in GitHub Desktop.
Recursive function example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} |
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
Thanks to quick bug report, logical error was corrected:
return factorial(n - 1)
replaced byreturn n * factorial(n - 1)
.