Beginner : C# recursive function

Asked

Viewed 2,655 times

1

help for Recursive Function that prints the average of the elements of an integer list and the number of elements larger than the average. in c#

good, what I have so far, is giving System.Stackoverflowexception error.

public static Double MediaLista(Double[] v)
{
    int i = 0;
    Double soma = 0;
    if (i < v.Length)
    {
        for (int j = 0; j < v.Length; j++)
        {
            soma += v[j];
        }
        i++;
        return soma / MediaLista(v);
    }
    else return 0;

}

static void Main(string[] args)
{
    Double[] v = {1,2,3,3,5};
    Double resul =  MediaLista(v);

}

Edit : I increased the functionality of taking the numbers larger than the average in the Medialist method itself. In all my method was like this.

        public static double MediaLista(int[] v, int ultimo)
    {
        if (ultimo == 0)
        {

            return v[0];
        }
        else
        {

            int qtdNumero = ultimo + 1;
            double soma = v[ultimo] + (qtdNumero - 1) * MediaLista(v, ultimo - 1);
            if (qtdNumero == v.Length) {
                for (int i = 0; i < v.Length; i++)
                {
                    if (v[i] > (soma / qtdNumero))
                    {
                        Console.WriteLine($"o numero {v[i]}  é maior que a média");
                    }
                }
            }

            return soma / qtdNumero;


        }

    }
  • Please add the code to your question.

  • Welcome to Stackoverflow. Take a look at tour from the site for some tips on how to formulate the question and make some changes to it, because the way it looks is that you want someone to do it for you instead of helping you.

  • 1

    opa, added

  • There’s probably a key lock left.

  • is on a loop, just as @Ronaldoaraújoalves said...

  • Return sum / Medialist(v); sum Return = 0 / 0 = overflow. Take your calculator there and divide 0 / 0. You will have undefined value or in c# stackoverflow pq no if tá lá que se i < v vai pro loop, se o i = 0 then you will never finish this.

  • Divide some number by 0 gives Dividebyzeroexception

  • Meeeeu God, I can’t believe I gaffed that kkkk, right. But I don’t understand why it’s recursive. The idea is to calculate the average of this list of elements and show those that are above this average point. Why call again? The next call is to calculate which are above the average and stop recursion there?

  • It’s an exercise in logic as I understand it. The idea is not the result, it’s training

  • It is, as I tbm am beginner in c# (came from Vb.net) to breaking the head here pq had never used recursiveness, but I managed to do even the media, missing to get which elements are bigger q the media.

  • Cool @Vanderleijunior , I took your logic to get the numbers bigger than the average and I incremented the average method. This should not change in function recursiveness.

Show 6 more comments

2 answers

1

StackOverflowException occurs when there is a overflow Stack memory, usually caused by over nested functions.

In the case on the line return soma / MediaLista(v); you didn’t change the vector at all v, causing it to call the method again, and again, and again..... until causing this exception. :)

I believe what you’re trying to do is return soma / v.Length;


EDIT

There is another mistake, this time of logic.

On the line soma += v[i]; you are making loop with the j but adding the element i, which is always 0.


EDIT 2.0 - Recursive Edition :P

Apparently it’s okay. :)

public static void Main()
{
    int[] v = { 1, 2, 9, 10, 25, 0};
    double media = Media(v, v.Length - 1);
    Console.Write(media);
}

public static double Media(int[] v, int ultimo)
{
    if (ultimo == 0)
        return v[0];

    int qtdNumero = ultimo+1;       
    double soma = v[ultimo] + (qtdNumero-1) * Media(v, ultimo-1);

    return soma/qtdNumero;
}
  • yes, but with ' Return sum / v.Length; ', it makes it a correct non-rerecursive function?

  • Right. I forgot about the need to be recursive. Pera que vou necessário reformular a resposta.

  • @Arlindocruzmachado edited the answer with the code

0

So I was able to do the recursion by taking the for and using if and instead of incrementing I was decreasing to recursion to get 0 and exit the loop and give me the result:

EDIT: I added the part that takes which elements are larger than the average

    private void MetroButton1_Click(object sender, EventArgs e)
    {
        double[] v = { 1, 2, 3, 3, 5 };
        double resul = MediaLista(v, v.Length, 0);
        //Elementos da array maiores do que a média
        string maiorMedia = string.Empty;
        for (int i = v.GetLowerBound(0); i <= v.GetUpperBound(0); i++)
        {
            if (v[i] > resul)
            {
                maiorMedia += v[i] + ",";                    
            }
        }
        metroLabel3.Text = Convert.ToString(resul);
        metroLabel4.Text = maiorMedia;

    }
    //média dos elementos de uma lista de inteiros
    public double MediaLista(double[] v, int tamanho, double media)
    {
        if (tamanho > 0)
        {                
            media = v[tamanho - 1] + MediaLista(v, tamanho - 1, media);
            if (tamanho == v.Length)
            {
                return media / v.Length;
            }
            return media;
        }
        else
            return 0;
    }

EDIT2:

Just to play a little more the part that takes which elements of the array are larger than the average, I made another option in LINQ for those who want to understand this feature that is widely used in Entity Framework and other Orms

        string maiorQueMedia = string.Empty;
        var query =
            from num in v
            where num > resul
            select num;
        foreach (double num in query)
            maiorQueMedia += num + ",";

Browser other questions tagged

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