Recursion
- C
- C++
src/c/basics/06-recursive-factorial.c
#include <stdio.h>
// long allows factorial up to 20
long factorial(int num)
{
if (num == 1)
return 1;
else
return (num * factorial(num - 1));
}
int main()
{
int lim = 10, i;
long fact;
for (i = 1; i < lim; i++)
{
fact = factorial(i);
printf("%d! = %ld\n", i, fact);
}
return 0;
}
src/cpp/basics/06-recursive-fibonacci.cpp
#include <iostream>
using namespace std;
long fibonacci(int n)
{
if (n <= 1)
return n;
else
return (fibonacci(n - 1) + fibonacci(n - 2));
}
int main()
{
int lim = 45, i;
long fib;
for (i = 0; i < lim; i++)
{
fib = fibonacci(i);
cout << "F(" << i << ") = " << fib << endl;
}
return 0;
}
info
Recursion enables us to solve certain types of problems very elegantly, however there are certain downside to large numbers of recursive function calls; it requires large amount of stack memory, and program might crash with stack overflow.