Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

C# C# Objects Loops and Final Touches For Loops

Erik Hainer
Erik Hainer
3,049 Points

I'm lost

I'm honestly not sure how to access the Tongue Length from the Frog class. Any tips on setting this up would be greatly appreciated.

FrogStats.cs
namespace Treehouse.CodeChallenges
{
    class FrogStats
    {
        public static double GetAverageTongueLength(Frog[] frogs)
        {
            int index = 0;
            for (int i = 0; i < frogs.Length; i++)
            {
                Frog frog = frogs[index];
                return TongueLength.Average;

            }
        }
    }
}
Frog.cs
namespace Treehouse.CodeChallenges
{
    public class Frog
    {
        public int TongueLength { get; }

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

1 Answer

Steven Parker
Steven Parker
216,012 Points

Probably the most common approach to getting an average is to add up all the individual values in a loop, and then after the loop finishes divide that sum by the number of items (the array length).

Also, you can use the loop variable as the index into the array. You won't need to create a separate index variable.

Inside the loop, to access the Tongue Length of a specific frog object, use frog.TongueLength.

Erik Hainer
Erik Hainer
3,049 Points

Thank you but what I'm wondering is how do I access the average of an array of class properties. I could get the average of frogs, but I don't know how to do the average tongue length.

Steven Parker
Steven Parker
216,012 Points

I don't think you can actually get an average of "frogs" (what would that mean, anyway?). But as I said, you can calculate an average if you get the frog.TongueLength of each one, and add those all up in a loop, and after the loop is done divide that sum by the number of frogs.