Patrick Aditya
Patrick Aditya

Reputation: 21

why is the recursion used in finding the factorial of a number?

Why can't we use it directly in main?
Why should there be a recursion?

#include<stdio.h>
int factorial(int n);
int main()
{
    int n;
    printf("Enter an positive integer: ");
    scanf("%d",&n);
    printf("Factorial of %d = %ld", n, factorial(n));
    return 0;
}

int factorial(int n)
{
    if(n!=1)
    return n*factorial(n-1);
}

Upvotes: 2

Views: 271

Answers (1)

Minor Threat
Minor Threat

Reputation: 2095

You don't have to use recursion. Because C doesn't support so-called optimization of tail recursion calls, you should avoid recursion where it could be replaced by a simple loop. But C does support recursion at all, and such factorial is the simpliest example of recursive function, if we don't pay attention to the fact that it is not an optimal code.

Simpliest usecase of recursion where it is actually needed could be a directory tree go-round. If you try to replace recursion with a loop in the latter case, you will get much less readable code and you're still gonna need a stack with O(N) memory where N is maximum directory nesting level, so, in most common cases, you wouldn't achieve anything useful from this optimisation attempt.

Also, pay attention to the fact that vanilla C lacks built-in support of dynamic data structures. You can, of course, implement a variable sized stack by using heap memory accessible via malloc(), realloc() and free() C runtime library's functions, but this approach will increase complexity of your project. You will have to look after your pointers to avoid leaks and memory corruption.

Upvotes: 5

Related Questions