Recursion leap of faith
unsigned long Factorial(unsigned int n)
{
unsigned long result = 1;
for (unsigned int i=2; i<=n; i++)
result *= i;
return result;
}
// or
unsigned long Factorial(unsigned int n)
{
if (n<2) // base case
return 1;
else
return (Factorial(n-1) * n);
}
double Power(int base, int exp)
{
double result = 1.0;
if (base==0)
{
printf("Error: power of 0 is undefined.");
result = 0;
}
else
{
unsigned int absExp = abs(exp);
for (unsigned int i=0; i<absExp; i++)
result *= base;
if (exp<0)
result = 1.0 / result;
}
return result;
}
// or
double Power(int base, int exp)
{
if (base==0)
{
printf("Error: power of 0 is undefined.");
return 0;
}
else (exp==0)
return 1.0;
elseif (exp<0)
return (Power(base, exp+1) / base);
else
return (Power(base, exp-1) * base);
}
Index