Reputation: 37
My question is regarding finding factorial of a number by using ternary operator in c. My code below suggests using recursion, in not the function definition, but the argument list. Is this valid in c ?
[Note : 0 factorial is handled by a seperate piece of code]
The function prototype for fact is :
int fact(int);
The definition would be :
int fact(num=(num>1)?num*fact(num-1):1)
{
return num;
}
My question is, just like recursion where a different instance of the same function is called within the function, can it be true for arguments too ?
Upvotes: 1
Views: 387
Reputation: 33601
Here are a few ways to do it [they will compile to pretty much the same--except the non-recursive version]:
// this is as close as you can come
int
fact(int num)
{
return ((num>1) ? num*fact(num-1) : 1);
}
// this also works
int
fact(int num)
{
if (num > 1)
num = num * fact(num-1);
return num;
}
// this also works
int
fact(int num)
{
if (num > 1)
num *= fact(num-1);
return num;
}
// non-recursive version
int
fact(int num)
{
int i;
int fac;
fac = 1;
for (i = 2; i <= num; ++i)
fac *= i;
return fac;
}
I should mention that the non-recursive version will execute faster. Ignoring that a large factorial might overflow an int
(i.e. long long
might be a better choice), try fact(100000000)
on a recursive version and you'll most likely segfault due to a stack overflow. But, the non-recursive one will handle that fine.
Upvotes: 0
Reputation: 7769
This is not a valid syntax, the compiler will complain about this because you are writing code implementation inside the argument area. The implementation has to be inside the curly brackets scope that follows the function signature
Example of valid syntax:
long factorial(int n);
// some code
long factorial(int n)
{
if (n == 0)
return 1;
else
return(n * factorial(n-1));
}
Reference: http://www.programmingsimplified.com/c-program-find-factorial
Upvotes: 1
Reputation: 24052
You want this:
int fact(int num)
{
return num > 1 ? num*fact(num-1) : 1;
}
Upvotes: 0