Here’s a program I wrote some time ago to teach functions, in particular to exemplify the difference between normal (using an iterative algorithm) and recursive functions. In this case, it is intended to calculate the values of the Fibonnaci sequence (see here for example).
/*
* Sequência de Fibonacci
* (de forma normal e de forma recursiva; esta última é bem mais lenta)
*
*/
#include <iostream>
using namespace std;
unsigned long long fibonacci(const unsigned int n){
unsigned long long resultado;
if (n==0)
resultado=0;
else if (n==1)
resultado=1;
else{
unsigned long long tabela[n+1];
tabela[0]=0;
tabela[1]=1;
for (auto i=2;i<=n;++i){
tabela[i]=tabela[i-2]+tabela[i-1];
}
resultado=tabela[n];
}
return resultado;
}
unsigned long long fibonacciRecursive(const unsigned int n){
if (n==0)
return 0;
else if (n==1)
return 1;
else
return(fibonacciRecursive(n-2)+fibonacciRecursive(n-1));
}
int main(){
unsigned int numero;
do{
cout << "Escolha numero (0 para terminar): ";
cin >> numero;
cout << "O numero de fibonnaci de ordem " << numero << " e " << fibonacci(numero) << endl;
cout << "O numero de fibonnaci de ordem " << numero << " e " << fibonacciRecursive(numero) << endl;
cout << endl;
}while(numero!=0);
return 0;
}
I can put here an example to streamline my question?
– Capitão Ahab
this link contains function versions for calculating whether a number is prime or not at compile time, requires advanced knowledge of c++: https://gist.github.com/oblitum/5692062
– pepper_chico