Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

C# C# Objects Loops and Final Touches For Loops

Nathan Reinauer
Nathan Reinauer
2,097 Points

For loop to get average isn't working

In the body of my for loop I have sum += frogs[i]; to add up all the values in the "frogs" array. However, it's not letting me do that because frogs is a Frog and not an int or double. But I'm only trying to pull a value out, and the value should be a number right? Not a "Frog". I try to cast with (int)frogs[i] or (double)frogs[i] but it doesn't like that either.

FrogStats.cs
namespace Treehouse.CodeChallenges
{
    class FrogStats
    {
        public static double GetAverageTongueLength(Frog[] frogs)
        {
            double sum;

            for(int i = 0; i < frogs.Length; i++)
            {
                sum += frogs[i]; 
            }

            return sum / frogs.Length;
        }
    }
}
Frog.cs
namespace Treehouse.CodeChallenges
{
    public class Frog
    {
        public int TongueLength { get; }

        public Frog(int tongueLength)
        {
            TongueLength = tongueLength;
        }
    }
}

1 Answer

Steven Parker
Steven Parker
231,248 Points

You want the average of the frog's tongue lengths, not the frogs themselves.

You're really close, and you've discovered that frog can't just be cast to a different type. But remember, you're not trying to average the frogs. So get the tongue length of each frog:

                sum += frogs[i].TongueLength;

Then just one more thing: you also forgot to set the initial value of sum (to zero).

Fix those and you should be good!

Nathan Reinauer
Nathan Reinauer
2,097 Points

Oh wow, you're right! Kind of a dumb mistake. Thanks for the explanation as well!