int iterativeFact(int number)
{
int factor = 1;
for (int count = 2; count <= number; count++)
factor = factor * count;
return factor;
}
int recursiveFact(int number)
{
if (number == 0)
return 1;
else
return number * recursiveFact(number - 1);
}
Iterative vs. Recursive implementation of the power function:
int IterPower(int base, int exponent)
{
int total = 1;
for (int i = 1; i <= exponent; i++)
total *= base;
return total;
}
int RecPower(int base, int exponent)
{
if (exponent == 0)
return 1;
else
return base * RecPower(base, exponent - 1);
}
Iterative vs. Recursive implementation of finding a maximum value in an array:
int IterMaxVal(int *array, int count)
{
int max = *array;
for (int i = 0; i < count; i++, ++array)
if (*array > max)
max = *array;
return max;
}
long X = 0; // For counting the number of recursive calls
int RecMaxVal(int *array, int count)
{
X++; // Count the number of recursive calls
if (count == 1)
return *array;
else if (*array > RecMaxVal(array + 1, count - 1))
return *array;
else
return RecMaxVal(array + 1, count - 1);
}