Problem with recursion and pointers

1

I'm having trouble solving the following question:

  

Make a recursive function that allows you to sum the even elements of a vector of integers, you must use pointers to traverse the vector

My code is not performing the correct calculations for the if condition of the somarpar function, it looks like this:

#include <stdio.h>
#include <stdlib.h>

int somarpar (int vet[], int n){
    int i=0, h=0, *pont=vet;


    for(i=0; i<n; i++){  

    if((pont[i]%2) == 0){

             h = pont[i] + somarpar(pont, n-1);

             }
        } return h;  
}

int main(int argc, char *argv[])
{   
    int somarpar(int vet[], int n);

    int vetor[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    int *p=vetor, z;

    z = somarpar(p, 10);

printf("a soma dos numeros pares eh: %i\n", z);

    system ("pause");

}

    
asked by anonymous 16.10.2017 / 16:54

2 answers

1

The code has several problems, some syntax.

Actually I consider exercise bad for recursion. It looks better with iteration.

So much so that it seems that I was putting a loop inside the recursive function.

I did not see need to use pointers in this algorithm.

You need to have a recursion closure condition ( n > 0 ) and the simple condition if it is even and should take this value or not.

#include <stdio.h>

int somarpar(int vet[], int n) {
    return n > 0  ? somarpar(vet, n - 1) + (vet[n] % 2 == 0 ? vet[n] : 0) : 0;
}

int main(void) {   
    int vetor[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    printf("a soma dos numeros pares eh: %i\n", somarpar(vetor, 10));
}

See running on ideone . And no Coding Ground . Also I put it in GitHub for future reference .

    
16.10.2017 / 17:13
1

First before going to the answer I would like to say that your program had several "errors", so first of all I would like to point them out just so you know where it went wrong.

#include <stdio.h>
#include <stdlib.h> /*  Você não utilizou nenhuma função desta biblioteca, não precisava
                        ter incluido-a  */

int somarpar ( int vet[], int n )
{
    int i = 0, h = 0, *pont = vet;  /*  seu exercico diz para usar ponteiro, logo não deve
                                        usar o i para controlar o indice do vetor, e sim
                                        aritimética de ponteiro */

    for ( i = 0; i < n; i++ )   {   /*  Você esta utilizando uma chamada recursiva, o que por si
                                        só já é um loop, for desnecessario, é aqui que faz o seu resultado
                                        sair maior do que o esperado.  */
        if((pont[i]%2) == 0)
        {
            h = pont[i] + somarpar(pont, n-1);
        }
    }

    return h;
}

int main (int argc, char *argv[])   /* você não utilizou nenhuma das duas variaveis, logo não deveria te-las aqui   */
{
    int somarpar(int vet[], int n); /*  declarou a função novamente, e além de tudo dentro da função main
                                        NÃO FAÇA ISSO!.  */

    int vetor[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    int *p=vetor, z;    /* não precisava fazer este ponteiro para o vetor   */

    z = somarpar(p, 10);

    printf("a soma dos numeros pares eh: %i\n", z);

    system ("pause");
                        /* esqueceu do return 0;    */
}

Taking into account the statement that asks to do a recursive function and also use pointer to walk in the index of the vector.

First we must understand what the exercise means by "you must use pointers to traverse the vector" , you should understand that what this exercise wants from you is that you use arithmetic from pointer to traverse the vector, ie without using a variable i for example, only with pointer. To do this is simple, you just know that a common vector is somehow a pointer, and also you just understand how a vector works, and how that is the calculation that the computer does to traverse the vector. So let's go, when you declare a vector of any type for example and want to loop through it, what you currently do is a loop where you start any variable (ex: i) at zero and then at the end it increases with one, but in the middle of the code you would do something like vet[i] , right, so what actually happens when you do this is vet[i] is equivalent to (tipo*)(vet + i) , note that you do a casting for the pointer type of your vector, and then sum your vector with the index you want to access.

Example, let's say you want to sum a vector of any integers, you have two ways to do it:

normal:

for ( i = 0, somatorio = 0; i < tam; ++i )
        somatorio += vet[i];

or

Using pointer arithmetic:

for ( ptrVet = (int*)(vetor), somatorio = 0; tam > 0; --tam, ptrVet = (int*)(ptrVet + 1) )
    somatorio += *ptrVet;

Both as I think you may notice are the same thing, the difference is that one omits the arithmetic of pointers that the computer does.

Well in the other part of the question he asks you to do a recursive function, ie in this case you are not using for , while or do while to loop, but recursion.

As you have used in your function I will consider that you already know how a recursive function works, but even then I will give you a brief simplified explanation.

A recursive function is a function that calls itself or another function in order to make a "loop", so that you can put an output condition inside a function and then call it recursively until the condition is reached. Example, let's assume you want to do a recursive multiplication function, so it would look that way.

int multiplicaNumero ( int x, int y )
{
    if ( y <= 1)        /*  Condição de saída   */
        return x;

    return x + multiplicaNumero(x, y - 1);
}

Explained this, if you have understood what I explained, it will be easy to understand how to do your exercise, so without further ado, here is the end result of your question, that would be the answer that I would consider right given the question, remembering that there are thousands of ways to do the same thing in C, so anything close to that would be correct.

#include <stdio.h>

int somarPar ( int vet[], int tam )
{
    int* ptrVet = (int*)(vet), soma = 0;

    if ( tam <= 0 )
        return 0;

    if ( *ptrVet % 2 == 0 )
        soma = *ptrVet;

    return soma + somarPar((int*)(ptrVet + 1), tam - 1);
}

int main ()
{
    int vetor[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    int tam = sizeof(vetor) / sizeof(vetor[0]);

    printf("a soma dos numeros pares eh: %i\n", somarPar(vetor, tam));

    system ("pause");

    return 0;
}

I hope I have helped;), good luck with C language studies.

    
17.10.2017 / 19:02