Recursive functions in C++: examples

Asked

Viewed 2,492 times

4

I am starting to learn C++ and I am currently focusing on recursive functions. I’ve seen some interesting examples, like the factorial calculation of a number, but I’d like to see other examples. I hope you will not consider this question too broad. It’s just about seeing and sharing other examples that might be useful to those learning the language. Thank you!

  • 2

    I can put here an example to streamline my question?

  • 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

1 answer

1

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;
}
  • +1 for example. Why use long long unisgned instead of int?

  • 2

    @Captain Hab Both fundamental types are integral but the unsigned long long allows dealing with values substantially higher than the int. In the C++ standard it is specified that the latter has a representation of at least 16 bits, whereas the one used in my program has at least 64 bits. The range of concrete values that each of the types admits depends on the implementation and the compiler. Making sizeof(type) allows checking the size (in Bytes) of them. In my case, int occupies 4 and unsigned long long occupies 8.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.