Recursion in C: Summation

1

I'm learning Recursion in C, and I need to do a recursive function that returns the sum of any n number. The function prototype is float somatorio(int n) and the sum to be calculated has the following formula: Σ (from i = 1 to i = n) {n / 1 + n}

So my question is: is the base case 1?     What about the summation calculation: How to define? I think it's something that starts with:

float somatorio(int n){
  float i;
    if( n == 1){
            return n;
        }else{
            i = n;
            i = (n / 1 + n) + somatorio(); // o que viria dentro da segunda parte?   (1 + n)?
            return i;
        }
}

Exercise definition: Image address: link

    
asked by anonymous 16.06.2017 / 02:12

1 answer

4

Yes the base case is 1.
The base case is the simplest case and you know what the return value is for that case. This is when your role starts to return a final element to the caller. In its problem the known and simplest case is when n = 1, since all summation in this case will end when n equals 1, in your problem we have that the sum of 1 is n / (1 + n) = > 1 / (2) = > 0.5. So let's say we want the sum of 5 would it be (5/6) + (4/5) + (3/4) + (2/3) + (1/2) correct? we can also think that the sum of 5 is: 5 / (1 + 5) + sum of 4. if we are to think that the sum of 4 is 4 / (1 + 4) + sum of 3 and so on then we would have: sum (5) = 5 / (1 + 5) + sum (4)
summation (4) = 4 / (1 + 4) + summation (3)
summation (3) = 3 / (1 + 3) + summation (2)
sum (2) = 2 / (1 + 2) + sum (1)
OPA! We know that the sum of 1 is 0.5 because it is our base case so then we would have:
sum (2) = 2 / (1 + 2) + 0.5 = > 1.1666 ...
then we know that summation (2) = 1.1666, and now we can calculate the sum of 3, of 4 and finally of 5.

I wrote a code example of the algorithm described above to try to demonstrate how it would look.

# include <stdio.h>
/*Função recursiva (calcula o somatorio de n)*/
float somatorio(int n)
{   
/*Veja que meu caso base é o somatório de 1
    e retorno o resultado que eu ja sei somatorio(1) = 1*/
    if (n == 1)
    {   
        return 0.5;
    }   
    /*Se não for meu caso base então eu 
    calculo o somatório do meu antecessor e somo o meu valor*/
    else 
    {   
        return ((float) n/(1+n) + somatorio(n-1));
    }   

}   

int main()
{   
    //Imprimo o resultado do somatorio de 5
    printf("%f", somatorio(5));
    return 0;
}   

I hope I have helped!

    
16.06.2017 / 03:04