Global variables recursion

Asked

Viewed 234 times

6

I’m learning recursion and have doubts about using global variables, particularly I think a gambit inelegant, maybe I’m wrong. I made a code to add positive numbers and used a variable called sum. I would like to know if there are other outputs for 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;
}

3 answers

6


In relation to recursiveness I can’t say whether 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 would particularly prefer not to use.

Here states that global variables can generate conflicts when working with threads, and this makes sense anyway, I would not use in this scenario, no one 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;
}

Exit

18

4

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);

4

You do not need to use the variable int soma, only an adjustment in the logic of its recursive function to sum 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:

Browser other questions tagged

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