Global variables recursion

4

I am learning recursion and I have doubts about using global variables, particularly I think a clumsy gambiarra , maybe you could be wrong. I made a code to add positive numbers and I used a variable called sum. I wonder if there are any other ways out of this question. Code below:

#include<stdio.h>

int soma = 0;

int SomaPositivos(int vet[], int n)  {
    if (n == 0) {
      return 0;
    } else { 
        int aux;
        if (vet[n-1] > 0) {     
            aux = vet[n-1];
            soma = soma + aux;
            SomaPositivos(vet, n-1);
        }
    }

    return soma;
}

int main () {   
    int v[20] = {2, 1, 8, 3, 4};
    int a;

    a = SomaPositivos(v, 5);
    printf("%d ", a);

    return 0;
}
    
asked by anonymous 29.01.2017 / 21:41

3 answers

5

Regarding recursion I do not know if it is "appropriate" to use global variables, even more so in your case, there are other ways to add the positives of the vector without having to use the global variable soma , I particularly preferred not to use .

Here states that global variables can generate conflicts when working with threads, and that makes sense, I would not use in this scenario, nobody has control of it.

I made an adaptation of your function based on this algorithm , see:

#include<stdio.h>

int SomaPositivos (int vet[], int n, int soma)
{
    if (n < 0)
    {
        return soma;
    }
    else
    {
        if (vet[n] > 0)
            soma += vet[n];
    }

    return SomaPositivos(vet, --n, soma);
}

int main(void)
{
    int v[20] = {-1, 2, 1, 8, 3, 4, -12};
    int a;
    int soma = 0;

    a = SomaPositivos (v, 7, soma);
    printf ("%d ", a);

    return 0;
}

Output

  

18

    
29.01.2017 / 22:12
4

You do not need to use the int soma variable, just an adjustment in the logic of your recursive function to add only the values that are positive :

#include <stdio.h>

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


int main(void) 
{
    int v[20] = {2, 1, 8, 3, 4, -6};
    int a;

    a = SomaPositivos(v, 6);
    printf("%d ", a);

    return 0;
}

Example Online

>

References:

29.01.2017 / 22:06
3

One possible alternative is to use an accumulator parameter:

int SomaPositivos(int soma, int vet[], int n)  {
    int somaAteAqui = soma;
    if (n <= 0) {
      return soma;
    } else { 
        int aux = vet[n-1];
        if (aux > 0) {   
            somaAteAqui += aux;
        }    
        somaAteAqui = SomaPositivos(somaAteAqui, vet, n - 1);
    }

    return somaAteAqui;
}

Sample call:

int resultado = somaPositivos(0, vet, 5);
    
29.01.2017 / 22:00