Recursion in c (factorial) example.

#include <stdio.h>

int factorial(int);

int main(int argc, char *argv[])
{
    if (argv < 1) 
        printf("Please enter in the console the number to see it's factorial");
    
    
    printf("%s", argv[1]);
    
    int fact = factorial(atoi(argv[1]));
    
    printf("The factorial of (%s) is (%d)", argv[1], fact);
    
    return 0;
}

int factorial(int number)
{
    if(number < 0)
        return 0;
    if(number == 0)
        return 1;
    
    return (number * factorial(number - 1));
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s